<?php

// +----------------------------------------------------------------------

// | Description: 客保部---员工评分和店面评分导出的页面逻辑

// +----------------------------------------------------------------------

// | Author: zl

// +----------------------------------------------------------------------



namespace app\crm\controller;



use app\admin\controller\ApiCommon;

use app\admin\model\ShopOrderModel;
use app\crm\model\BalanceLog;

use app\crm\model\CustomerAnalyseModel;

use app\crm\model\Customer as CustomerModel;

use app\crm\model\CustomerConfig as CustomerConfigModel;

use app\crm\model\Service;
use app\crm\model\ServiceLog;
use app\crm\model\ServiceOrderSendLog;
use app\crm\model\ShopGoods;
use app\crm\model\ShopOrderGoods;
use app\shop\model\Refund;
use think\response\Json;

use think\facade\Db;


use app\common\traits\ActionRecordTrait;

use app\crm\model\CustomerInfoAPI as CustomerInfoAPIModel;//引用EC接口文档

use app\crm\model\ReserveandLost;

use app\mini\model\SendUrlModel;

use app\admin\model\ShopModel;

class CustomerYucun extends ApiCommon

{
    protected $customerModel;

    protected $customerConfigModel;

    /**

     * 用于判断权限

     * @permission 无限制

     * @allow 登录用户可访问

     * @other 其他根据系统设置

     **/

    public function initialize()

    {

        $action = [

            'permission' =>
                [
                    'setCustomerZTYuCun',
                    'setCustomerKXYuCun',
                    'setCustomerDJYuCun',
                    'setjsmaktingyc',
                    'setzxunmaktingyc',
                    'setjmbjmaktingyc',
                    'setCustomerCYYuCun',
                    'setzgtmaktingyc',
                    'setcdcqmaktingyc',
                    'setCustomerJSYuCun',
                    'setCustomerZCYYuCun',
                    'setCustomerBJYYuCun',
                    'setCustomerZHUXUNYuCun',
                    'setcustomeryucunkunming',
                    'setztmaktingyc',
                    'setkmxianmaktingyc',
                    'setdjmaktingyc',
                    'setcustomerdongbei',
                    'customer_tj',
                    'set_ceshi',
                    'execute',
                    'send_msg',
                    'shop_yj',
                    'aclass_total_periodicity',
                    'bclass_total_periodicity',
                    'customer_total_consumption',
                    'shop_total_periodicity',
                    'verify',
                    'md_mz_yj',
                    'shop_total_periodicity1',
                    'change_customer_total_consumption',
                    'aclass_total',
                    'bclass_total',
                    'aclass_periodicity',
                    'bclass_periodicity',
                    'shop_total',
                    'shop_periodicity',
                    'shop_performance_new',
                    'mz_customer_consume',
                    'md_customer_consume',
                    'md_one_customer_consume',
                    'md_two_customer_consume',
                    'change_point_status',
                    'shop_performance',
                    'customer_consumption',
                    'customer_balance_reset',
                    'customer_balance_clear',
                    'customer_balance_unique',
                    'setservicelogorderout'
                ],
            'allow' => ['users', 'info']
        ];

        event('CheckAuth',$action);

        $request = $this->request;

        $a = strtolower($request->action());



        $this->customerModel = new CustomerModel();

        $this->customerConfigModel = new CustomerConfigModel();

        if (!in_array($a, $action['permission'])) {

            parent::initialize();

        }

    }

    //处理核销记录产出出库单推送
    public function setServiceLogOrderOut(){
        Db::startTrans();
        try {
            $serviceLog = ServiceLog::where('is_cancel',0)->where('is_send',0)->limit(50)->select()->toArray();
            if(empty($serviceLog)){
              throw new \Exception('暂无核销记录');
            }

            $cjyh_goods = ShopGoods::where('kingdee_code','101.12.098')->cache(true)->find();//冲减优惠

            $serviceModel = new Service();
            $insertLogArr = [];
            foreach($serviceLog as $k=>$v){
                $serviceModel = clone $serviceModel;
                $serviceInfo = $serviceModel->where('id',$v['service_id'])->find();
                list($shopOrder,$shopRefundOrderGoods,$cjyh)=  $serviceModel->getServiceOrder($serviceInfo);
                $data = [
                    'uid'                =>  $shopOrder['uid'], // 客户
                    'uid_source_type_id' =>  $shopOrder['source_type_id'],
                    'uid_source_id'      =>  $shopOrder['source_id'],
                    'consignee'          => trim($shopOrder['consignee']), // 收货人
                    'order_no'           => 'HX'.time().rand(1000,9999), // 订单号
                    'sale_id'            => $shopOrder['sale_id'], // 销售员id
                    'sale_name'          => trim($shopOrder['sale_name']), // 销售员姓名
                    'shop_id'            => $shopOrder['shop_id'], // 门店id
                    'shop_name'          => trim($shopOrder['shop_name']), // 门店名称
                    'operator_id'        => $shopOrder['operator_id'],//制单员id
                    'operator_name'      => $shopOrder['operator_name'],//制单员姓名
                    'create_time'       => time(), // 创建时间
                    'deal_time'         => strtotime(date('Y-m-d',strtotime($v['create_time']))), // 成交日期
                    'goods_price'       => 0, // 订单标准金额 之和
                    'order_amount'      => bcadd($v['real_cancel_balance'],$v['real_cancel_gift'],2),
                    'total_amount'      => bcadd($v['real_cancel_balance'],$v['real_cancel_gift'],2), // 订单总金额 之和
                    'pay_amount'        => $v['real_cancel_balance'], // 实收本金
                    'gift_amount'       => $v['real_cancel_gift'], // 实收赠金
                    'description'           => '核销记录产出出库单', // 订单描述
                    'order_type'            => 2, // 订单类型 1新单 2补单
                    'income_type'           => $shopOrder['income_type'], // 收入类型 1 服务（各类疗程卡项及疗程卡项赠送产品）2 产品销售（单独付费购买产品）3 医美收入
                    'sales_policy'          => $shopOrder['sales_policy'], // 销售政策编码
                    'market_id'             => $shopOrder['market_id'] , // 市场id
                    'market_name'           => $shopOrder['market_name'], // 市场名称
                    'sales_organization'    => $shopOrder['sales_organization'] , // 销售组织编码
                    'sales_name'            => $shopOrder['sales_name'] , // 销售组织名称
                    'settlement_organization' => $shopOrder['settlement_organization'],// 结算组织编码
                    'settlement_name'       => $shopOrder['settlement_name'], // 结算组织名称
                    'delivery_name'       => $shopOrder['delivery_name'], // 发货部门名称
                    'delivery_king'       => $shopOrder['delivery_king'], // 发货部门编码
                    'api_type' => 3, //0中台系统 1商城积分兑换订单 2商城普通订单  3 核销记录出库单
                    'service_log_id' => $v['id'] //服务记录
                ];
                $order = ShopOrderModel::create($data);

                $orderGoodsList = [];
                $orderGoodsList['pay_amount'] = $v['consume_money'];
                $orderGoodsList['gift_amount'] = $v['consume_gratuity'];
                $orderGoodsList['order_id'] = $order->id;
                $orderGoodsList['create_time'] = time();
                $orderGoodsList['goods_id'] = $shopRefundOrderGoods['goods_id'];
                $orderGoodsList['goods_name'] = $shopRefundOrderGoods['goods_name'];
                $orderGoodsList['kingdee_code'] = $shopRefundOrderGoods['kingdee_code'];
                $orderGoodsList['goods_price'] = $shopRefundOrderGoods['goods_price'];
                $orderGoodsList['pay_price'] = bcadd($v['consume_money'], $v['consume_gratuity'],2); //售卖价格
                $orderGoodsList['spec_name'] = $shopRefundOrderGoods['spec_name'];
                $orderGoodsList['unit_code'] = $shopRefundOrderGoods['unit_code'];
                $orderGoodsList['unit_name'] = $shopRefundOrderGoods['unit_name'];
                $orderGoodsList['number'] = 1;
                $orderGoodsList['desc'] = '核销记录-产出出库单明细';
                $orderGoodsList['is_project'] = 1;//是否服务 1 是 2否
                $orderGoodsList['category_id'] = $shopRefundOrderGoods['category_id'];
                $orderGoodsList['is_coupon_goods'] = 0;//是否优惠券商品 0否 1是
                $orderGoodsList['project_type'] = 1;//服务类型 1 按次 2按天
                $orderGoodsList['service_number'] = 1;//服务次数
                $orderGoodsList['is_gift'] = $shopRefundOrderGoods['is_gift'];  //是否为赠品
                $orderGoodsList['house_code'] =  $shopRefundOrderGoods['house_code'];
                $orderGoodsList['house_code_name'] = $shopRefundOrderGoods['house_code_name'];
                $orderGoodsList['goods_alias_name'] = $shopRefundOrderGoods['goods_alias_name'];
                $orderGoodsList['prestock_type'] = 1; //预存货类型
                $orderGoodsList['takeout_stock_num'] = 1;  //出货数量
                $orderGoodsList['data_business_type'] = $shopRefundOrderGoods['data_business_type'];  //业务类型
                $orderGoodsList['data_business_two_type'] = 0;  //业务类型
                $orderGoodsList['discount_amount'] = 0;  //折扣金额
                $orderGoodsList['after_discount_amount'] = bcadd($v['real_cancel_balance'], $v['real_cancel_gift'],2);  //优惠后金额
                $order_goods_res = ShopOrderGoods::create($orderGoodsList);

                if(!empty($cjyh)){
                    $orderGoodsList = [];
                    $orderGoodsList['pay_amount'] = abs($v['discount_amount']);
                    $orderGoodsList['gift_amount'] = 0;
                    $orderGoodsList['shop_transfer_amount'] = 0;
                    $orderGoodsList['order_id'] = $order->id;
                    $orderGoodsList['create_time'] = time();
                    $orderGoodsList['goods_id'] = $cjyh_goods['id'];
                    $orderGoodsList['goods_name'] = $cjyh_goods['name'];
                    $orderGoodsList['kingdee_code'] = $cjyh_goods['kingdee_code'];
                    $orderGoodsList['goods_price'] = $cjyh_goods['goods_price'];
                    $orderGoodsList['pay_price'] = abs($v['discount_amount']); //售卖价格
                    $orderGoodsList['spec_name'] = $cjyh_goods['spec_name'];
                    $orderGoodsList['unit_code'] = $cjyh_goods['unit_code'];
                    $orderGoodsList['unit_name'] = $cjyh_goods['unit_name'];
                    $orderGoodsList['number'] = $v['discount_amount'] < 0 ?-1:1;
                    $orderGoodsList['desc'] = '核销记录-产出出库单明细-冲减优惠';
                    $orderGoodsList['is_project'] = 2;//是否服务 1 是 2否
                    $orderGoodsList['category_id'] = $cjyh_goods['category_id'];
                    $orderGoodsList['is_coupon_goods'] = 0;//是否优惠券商品 0否 1是
                    $orderGoodsList['project_type'] = 0;//服务类型 1 按次 2按天
                    $orderGoodsList['service_number'] = 0;//服务次数
                    $orderGoodsList['is_gift'] = 0;  //是否为赠品
                    $orderGoodsList['house_code'] =  $shopRefundOrderGoods['house_code'];
                    $orderGoodsList['coupon_type'] = 0;//优惠券类型
                    $orderGoodsList['house_code_name'] = $shopRefundOrderGoods['house_code_name'];
                    $orderGoodsList['goods_alias_name'] = $shopRefundOrderGoods['goods_alias_name'];
                    $orderGoodsList['prestock_type'] = 1; //预存货类型
                    $orderGoodsList['takeout_stock_num'] = 1;  //出货数量
                    $orderGoodsList['data_business_type'] = $shopRefundOrderGoods['data_business_type'];  //业务类型
                    $orderGoodsList['data_business_two_type'] = 0;  //业务类型
                    $orderGoodsList['discount_amount'] = 0;  //折扣金额
                    $orderGoodsList['after_discount_amount'] = 0;  //优惠后金额
                    $order_goods_res = ShopOrderGoods::create($orderGoodsList);
                }

                $insertLog = [
                    'service_log_id'=>$v['id'],
                    'customer_id'=>$v['customer_id'],
                    'order_id'=>$order->id,
                    'is_send'=>0,
                    'create_time'=>time()
                ];
                $refundModel = new Refund();
                $refundModel->sendYxk($v['customer_id'],5,$order->id);
                $insertLog['is_send'] = 2;
                $insertLog['send_time'] = time();
                array_push($insertLogArr,$insertLog);

                DB::name('service_log')->where('id',$v['id'])->update(['order_id'=>$order->id,'is_send'=>1]);

            }
            ServiceOrderSendLog::insertAll($insertLogArr);

            Db::commit();
            echo "操作成功";

        }catch (Exception $e){
            Db::rollback();
            echo $e->getMessage();die;
        }

    }


	//郑太市场预存 -- 郑州直管3 + 郑州直营(含中医院)3+太原3   郑州万达+正弘店+金水总院+公园茂店+航海路+ 云路街+体育路+平阳路 +中医院
   public function setCustomerZTYuCun(){

	    //echo '客户预存信息页面';echo '<br/>';
	    $time = date('Ymd');

	    $zyShopIds = [73782774859952,76520948050011,78870916600002,78852178480703,73782774813542,73782774707242,73782774791259,73782774742277,73782774881835];
	    //查询有预存的客户
		$zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
		//查询当天时间这些门店 是否已经有客户新增成功
		$zyYC = Db::name('customer_balance_tj')->where('time','=',$time)->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');

		//客户ID进行去重
		$customerIds = array_diff($zyB, $zyYC);

		$zyByc = Db::name('customer_balance')->where('customer_id','in',$customerIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_transfer_money,shop_id');

	    $b = ['time'=>$time];
	    array_walk($zyByc, function(&$val, $key) use ($b) {
	       $val = array_merge($val, $b);
	    });

	   $res = Db::name('customer_balance_tj')->insertAll($zyByc);

	   return resultArray(['data'=>[],'error'=>'处理成功']);



   }
   	//昆西市场预存  昆明南宁 6 + 西安 4
	public function setCustomerKXYuCun(){
		$time = date('Ymd');

		$zyShopIds = [73782775132896,73782775140871,73782775247649,73782775295382,73782775222970,73782775241316,73782775206631,73782775392774,73782775131388];
		//查询有预存的客户
		$zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
		//查询当天时间这些门店 是否已经有客户新增成功
		$zyYC = Db::name('customer_balance_tj')->where('time','=',$time)->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');

		//客户ID进行去重
		$customerIds = array_diff($zyB, $zyYC);

		$zyByc = Db::name('customer_balance')->where('customer_id','in',$customerIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_transfer_money,shop_id');

	    $b = ['time'=>$time];
	    array_walk($zyByc, function(&$val, $key) use ($b) {
	       $val = array_merge($val, $b);
	    });


		$res = Db::name('customer_balance_tj')->insertAll($zyByc);

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}
	//东北 6 + 京津 3  + 成都门诊1
	public function setCustomerDJYuCun(){
		$time = date('Ymd');

		$zyShopIds = [73782775074894,73782775019638,73782775492343,73782775012531,73782775013838,73782775096910,73782775102252,73782775155221,73782775133028,73782775085647];
		//查询有预存的客户
		$zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
		//查询当天时间这些门店 是否已经有客户新增成功
		$zyYC = Db::name('customer_balance_tj')->where('time','=',$time)->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');

		//客户ID进行去重
		$customerIds = array_diff($zyB, $zyYC);

		$zyByc = Db::name('customer_balance')->where('customer_id','in',$customerIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_transfer_money,shop_id');

	    $b = ['time'=>$time];
	    array_walk($zyByc, function(&$val, $key) use ($b) {
	       $val = array_merge($val, $b);
	    });

		$res = Db::name('customer_balance_tj')->insertAll($zyByc);

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}
	//成都 4 +重庆 5  直营门店    江北店+沙坪坝+南坪店+大坪店+杨家坪 ++ 总府店+龙湖店+文殊店+菊乐店+环球店
	public function setCustomerCYYuCun(){
		$time = date('Ymd');

		$zyShopIds = [73782774937394,73782774939196,73782774982253,73782774973465,73782774988622,73782774957269,73782775030746,73782775078712,73782775070582];
		//查询有预存的客户
		$zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
		//查询当天时间这些门店 是否已经有客户新增成功
		$zyYC = Db::name('customer_balance_tj')->where('time','=',$time)->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');

		//客户ID进行去重
		$customerIds = array_diff($zyB, $zyYC);

		$zyByc = Db::name('customer_balance')->where('customer_id','in',$customerIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_transfer_money,shop_id');

	    $b = ['time'=>$time];
	    array_walk($zyByc, function(&$val, $key) use ($b) {
	       $val = array_merge($val, $b);
	    });

		$res = Db::name('customer_balance_tj')->insertAll($zyByc);

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}

	//济南5 +石家庄 5
	public function setCustomerJSYuCun(){
		$time = date('Ymd');

		$zyShopIds = [73782775249465,73782775342427,73782776799504,73782775382480,73782775368291,73782775339453,73782775382138,73782775394959];
		//查询有预存的客户
		$zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
		//查询当天时间这些门店 是否已经有客户新增成功
		$zyYC = Db::name('customer_balance_tj')->where('time','=',$time)->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');

		//客户ID进行去重
		$customerIds = array_diff($zyB, $zyYC);

		$zyByc = Db::name('customer_balance')->where('customer_id','in',$customerIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_transfer_money,shop_id');

	    $b = ['time'=>$time];
	    array_walk($zyByc, function(&$val, $key) use ($b) {
	       $val = array_merge($val, $b);
	    });

		$res = Db::name('customer_balance_tj')->insertAll($zyByc);

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}

	//郑州直营4 +郑州直管 3+ 成都2（攀成钢+光环）+烟台莱山1    玉凤路+文化路+天明路+建设西路+三全路店+商业中心店+升龙城店
	public function setCustomerZCYYuCun(){
		$time = date('Ymd');

		$zyShopIds = [73782774822370,73782774813357,73782774896742,73782774880422,78872028809917,79085556716103,78808830816801,79958737536305,73782776396518,79234669613042];
		//查询有预存的客户
		$zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
		//查询当天时间这些门店 是否已经有客户新增成功
		$zyYC = Db::name('customer_balance_tj')->where('time','=',$time)->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');

		//客户ID进行去重
		$customerIds = array_diff($zyB, $zyYC);

		$zyByc = Db::name('customer_balance')->where('customer_id','in',$customerIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_transfer_money,shop_id');

	    $b = ['time'=>$time];
	    array_walk($zyByc, function(&$val, $key) use ($b) {
	       $val = array_merge($val, $b);
	    });

		$res = Db::name('customer_balance_tj')->insertAll($zyByc);

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}

	//加盟门店 8家（烟青潍坊8家）
	public function setCustomerBJYYuCun(){
		$time = date('Ymd');

		$zyShopIds = [73782776714906,73782776780645,73782776735183,73782776723608,73782776866322,78144422942919,78153925370743,73782775923594,73782775246614,73782775223895];
		//查询有预存的客户
		$zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
		//查询当天时间这些门店 是否已经有客户新增成功
		$zyYC = Db::name('customer_balance_tj')->where('time','=',$time)->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');

		//客户ID进行去重
		$customerIds = array_diff($zyB, $zyYC);

		$zyByc = Db::name('customer_balance')->where('customer_id','in',$customerIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_transfer_money,shop_id');

	    $b = ['time'=>$time];
	    array_walk($zyByc, function(&$val, $key) use ($b) {
	       $val = array_merge($val, $b);
	    });

		$res = Db::name('customer_balance_tj')->insertAll($zyByc);

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}

	//处理预存
	/*
	 @*  百花店+巩义店+石家庄门诊+济南门诊+重庆门诊+大学路+江北店
	 @*  十里铺已经闭店-2024-6月；新疆万达店 不在续费 关闭；光华店 闭店
	*/
	public function setCustomerZHUXUNYuCun(){  //
		$time = date('Ymd');

		$zyShopIds = [73782777060245,73782776104831,73782775377728,73782775392774,73782774991693,73782774834649,73782774982464,82102481001860,73782775159891];
		//查询有预存的客户
		$zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');
		//查询当天时间这些门店 是否已经有客户新增成功
		$zyYC = Db::name('customer_balance_tj')->where('time','=',$time)->where('shop_id','in',$zyShopIds)->distinct('customer_id')->column('customer_id');

		//客户ID进行去重
		$customerIds = array_diff($zyB, $zyYC);

		$zyByc = Db::name('customer_balance')->where('customer_id','in',$customerIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_transfer_money,shop_id');

	    $b = ['time'=>$time];
	    array_walk($zyByc, function(&$val, $key) use ($b) {
	       $val = array_merge($val, $b);
	    });

		$res = Db::name('customer_balance_tj')->insertAll($zyByc);

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}

	public function customer_tj()
	{
		$model = new ReserveandLost();

		$today = date('Y-m-d',time());

		$nowDate = date("Ymd",time());

		// 获取门店shop_ids
		$shop_ids = Db::name('shop')->where([['type','=',1],['status','=',1],['shop_type','=',2],['shop_id','<>','74076159037951']])->column('shop_id');

		$list = [];

		foreach ($shop_ids as $key => $value) {

			$where = [];

			array_push($where,['shop_id','=',$value]);

			array_push($where,['date','=',$nowDate]);

			$data = Db::name('customer_tj')->where($where)->select()->toArray();

			if($data){

			}else{

				$one = [];

				$shopIds = [];

				array_push($shopIds,$value);

				// 总成交顾客数
				$cj_customer = $model->cj_customer($shopIds,[]);

				// 保有顾客数
				$baoyou_customer = $model->baoyou_customer($cj_customer,$today);

				// 流失顾客数
				$lost_customer = $model->lost_customer($cj_customer,$today);

				// 流失预警顾客
				$warning_customer = $model->warning_customer($cj_customer,$today,'','','');


				$one['shop_id'] = $value;

				$one['date'] = $nowDate;

				$one['cj_customer_ids'] = implode(',',$cj_customer) ?? '';

				$one['baoyou_customer_ids'] = implode(',',$baoyou_customer) ?? '';

				$one['lost_customer_ids'] = implode(',',$lost_customer) ?? '';

				$one['warn_customer_ids'] = implode(',',$warning_customer) ?? '';

				$one['create_time'] = time();

				array_push($list,$one);

			}



		}

		// echo "<pre>";
		// print_r($list);
		// echo "</pre>";

		if($list){

			$res = Db::name('customer_tj')->insertAll($list);

		}

		return resultArray(['data'=>[],'error'=>'处理成功']);
		// var_dump($res);
	}

	public function set_ceshi()
	{
		$addDate = [
			'tag_name' => date("Y-m-d H:i:s",time()),
			'customer_id' => '141222',
			'staff_name' => 'zhangsan',
			'create_time' => date("Y-m=d H:i:s",time()),
			'type' => '0',
		];

		$res = Db::name('customer_tag')->insert($addDate);

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}

	//处理品相信息
	public function setOrderGoodsAnalyse()
	{
		$extra = [170];

		$start_time = strtotime(date('Y-m-d',strtotime('-1 day')));
		$end_time = $start_time+24*60*60-1;

		Db::startTrans();
		try{
			$where = [];
			array_push($where,['b.status','=',2]);
			array_push($where,['a.goods_id','not in',$extra]);
			array_push($where,['b.deal_time','>=',$start_time]);
			array_push($where,['b.deal_time','<=',$end_time]);

			$res = Db::name('shop_order_goods')
				->field('b.shop_id,b.uid,a.goods_id,a.number,a.pay_price')
				->alias('a')
				->join('shop_order b','a.order_id = b.id','LEFT')
				// ->join('shop_goods c','a.goods_id = c.id')
				// ->join('shop d','a.shop_id = d.shop_id')
				->where($where)
				// ->group('b.shop_id,a.goods_id')
				->select()->toArray();
			$firstData = [];
			foreach($res as $value)
			{
				$arr = [];
				if(empty($firstData[$value['shop_id']][$value['goods_id']]))
				{
					$firstData[$value['shop_id']][$value['goods_id']]['number'] = 1;
					$firstData[$value['shop_id']][$value['goods_id']]['uid'] = [];
					array_push($firstData[$value['shop_id']][$value['goods_id']]['uid'],$value['uid']);
					$firstData[$value['shop_id']][$value['goods_id']]['repurchase_num'] = 1;
					$firstData[$value['shop_id']][$value['goods_id']]['total_amount'] = $value['number']*$value['pay_price'];
				}else{
					$firstData[$value['shop_id']][$value['goods_id']]['number'] += 1;
					$firstData[$value['shop_id']][$value['goods_id']]['repurchase_num'] += 1;
					if(!in_array($value['uid'],$firstData[$value['shop_id']][$value['goods_id']]['uid']))
					{
						array_push($firstData[$value['shop_id']][$value['goods_id']]['uid'],$value['uid']);
					}
					$firstData[$value['shop_id']][$value['goods_id']]['total_amount'] += $value['number']*$value['pay_price'];
				}
			}
			$insertData = [];
			foreach($firstData as $key => $value)
				foreach($value as $k => $v)
				{
					$arr = [
						'shop_id' =>$key,
						'goods_id' =>$k,
						'number' => count($v['uid']),
						'repurchase_num' => $v['repurchase_num'],
						'total_amount' =>$v['total_amount'],
						'deal_time'=>$start_time
					];
					array_push($insertData,$arr);
				}
			 $res = Db::name('shop_goods_analyse')->insertAll($insertData);

			$where = [];
			array_push($where,['b.status','=',2]);
			array_push($where,['a.goods_id','not in',$extra]);
			array_push($where,['b.deal_time','>=',$start_time]);
			array_push($where,['b.deal_time','<=',$end_time]);

			$res = Db::name('shop_order_goods')
				->field('b.shop_id,b.uid,c.goods_type,a.number,a.pay_price')
				->alias('a')
				->join('shop_order b','a.order_id = b.id','LEFT')
				->join('shop_goods c','a.goods_id = c.id')
				->where($where)
				->select()->toArray();


			$firstData = [];
			foreach($res as $value)
			{
				$arr = [];
				if(empty($firstData[$value['shop_id']][$value['goods_type']]))
				{
					$firstData[$value['shop_id']][$value['goods_type']]['number'] = 1;
					$firstData[$value['shop_id']][$value['goods_type']]['uid'] = [];
					array_push($firstData[$value['shop_id']][$value['goods_type']]['uid'],$value['uid']);
					$firstData[$value['shop_id']][$value['goods_type']]['repurchase_num'] = 1;
					$firstData[$value['shop_id']][$value['goods_type']]['total_amount'] = $value['number']*$value['pay_price'];
				}else{
					$firstData[$value['shop_id']][$value['goods_type']]['number'] += 1;
					$firstData[$value['shop_id']][$value['goods_type']]['repurchase_num'] += 1;
					if(!in_array($value['uid'],$firstData[$value['shop_id']][$value['goods_type']]['uid']))
					{
						array_push($firstData[$value['shop_id']][$value['goods_type']]['uid'],$value['uid']);
					}
					$firstData[$value['shop_id']][$value['goods_type']]['total_amount'] += $value['number']*$value['pay_price'];
				}
			}
			$insertData = [];
			foreach($firstData as $key => $value)
				foreach($value as $k => $v)
				{
					$arr = [
						'shop_id' =>$key,
						'goods_type' =>$k,
						'number' => count($v['uid']),
						'repurchase_num' => $v['repurchase_num'],
						'total_amount' =>$v['total_amount'],
						'deal_time'=>$start_time
					];
					array_push($insertData,$arr);
				}
			$res = Db::name('shop_goods_analyse')->insertAll($insertData);

			$where = [];

			array_push($where,['status','=',4]);
			array_push($where,['cancel_time','<>',0]);
			array_push($where,['cancel_time','>=',$start_time]);
			array_push($where,['cancel_time','<',$end_time]);

			$res = Db::name('shop_order')->where($where)->select()->toArray();


			foreach($res as $value)
			{
				if(date('Y-m-d',$value['deal_time']) == date('Y-m-d',$value['cancel_time']))
					{
						continue;
					}
				$orderId = $value['id'];
				$where = [];
				array_push($where,['a.order_id','=',$orderId]);

				$orderGoods = Db::name('shop_order_goods')->alias('a')
					->field('a.goods_id,b.goods_type,a.number,a.pay_price')
					->join('shop_goods b','a.goods_id = b.id')
					->where($where)->find();


				$where = [];
				array_push($where,['shop_id','=',$value['shop_id']]);
				array_push($where,['goods_id','=',$orderGoods['goods_id']]);
				array_push($where,['deal_time','=',strtotime(date('Y-m-d',$value['deal_time']))]);
				$orderGoodsAnalyse = Db::name('shop_goods_analyse')->where($where)->find();
				$UpdateorderGoodsAnalyse['repurchase_num']=$orderGoodsAnalyse['repurchase_num']-1;
				$UpdateorderGoodsAnalyse['total_amount']=$orderGoodsAnalyse['total_amount']-$orderGoods['number']*$orderGoods['pay_price'];

				$where = [];
				array_push($where,['b.uid','=',$value['uid']]);
				array_push($where,['b.deal_time','>=',$value['deal_time']]);
				array_push($where,['b.deal_time','<=',$value['deal_time']+24*60*60-1]);
				array_push($where,['b.shop_id','=',$value['shop_id']]);
				array_push($where,['a.goods_id','=',$orderGoods['goods_id']]);
				$orderGoodsData = Db::name('shop_order_goods')->alias('a')
					->field('a.goods_id,count(b.uid) as num')
					->join('shop_order b','a.order_id = b.id')
					->group('b.uid')
					->where($where)->find();
				if($orderGoodsData['num'] == 1)
				{
					$UpdateorderGoodsAnalyse['number']=$orderGoodsAnalyse['number']-1;
				}

				$where = [];
				array_push($where,['id','=',$orderGoodsAnalyse['id']]);
				 $res = Db::name('shop_goods_analyse')->where($where)->update($UpdateorderGoodsAnalyse);

				$where = [];
				array_push($where,['shop_id','=',$value['shop_id']]);
				array_push($where,['goods_id','=',0]);
				array_push($where,['goods_type','=',$orderGoods['goods_type']]);
				array_push($where,['deal_time','=',strtotime(date('Y-m-d',$value['deal_time']))]);
				$orderGoodsAnalyse = Db::name('shop_goods_analyse')->where($where)->find();
				$UpdateorderGoodsAnalyse['repurchase_num']=$orderGoodsAnalyse['repurchase_num']-1;
				$UpdateorderGoodsAnalyse['total_amount']=$orderGoodsAnalyse['total_amount']-$orderGoods['number']*$orderGoods['pay_price'];

				$where = [];
				array_push($where,['b.uid','=',$value['uid']]);
				array_push($where,['b.deal_time','>=',$value['deal_time']]);
				array_push($where,['b.deal_time','<=',$value['deal_time']+24*60*60-1]);
				array_push($where,['b.shop_id','=',$value['shop_id']]);
				array_push($where,['c.goods_type','=',$orderGoods['goods_type']]);
				$orderGoodsData = Db::name('shop_order_goods')->alias('a')
					->field('c.goods_type,count(b.uid) as num')
					->join('shop_order b','a.order_id = b.id')
					->join('shop_goods c','a.goods_id = c.id')
					->group('b.uid')
					->where($where)->find();

				if($orderGoodsData['num'] == 1)
				{
					$UpdateorderGoodsAnalyse['number']=$orderGoodsAnalyse['number']-1;
				}

				$where = [];
				array_push($where,['id','=',$orderGoodsAnalyse['id']]);
				$res = Db::name('shop_goods_analyse')->where($where)->update($UpdateorderGoodsAnalyse);

			}




			Db::commit();
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			return json($e->getMessage());
		}
	}
	/**
	 * 客服分析表
	 */
    public function setCustomerAnalyse($date)
    {
        $now = date('Y-m-d',strtotime('-1 day'));

        $bh = [1,2,3,4,5,6,7,8,9];
        $dd = [10];
        $xm = [11,12];

        $start_time = strtotime($date);
        $end_time = strtotime($date)+24*60*60-1;
        $data = [];
        $baseWhere = [];
        $whereOr = [];
        array_push($whereOr,['a.first_time','between',[$start_time,$end_time]]);
        array_push($whereOr,['a.second_time','between',[$start_time,$end_time]]);
        if(!empty($request['shopIds']))
        {
            array_push($baseWhere,['a.shop_id','in',$request['shopIds']]);
        }
        $where = array_merge($baseWhere,[['b.customer_setting_id_type','in',$bh]]);
        $res = Db::name('customer')->alias('a')
            ->join('customer_scar b','a.id = b.customer_id','left')
            ->join('shop c','a.shop_id = c.shop_id','left')
            ->field('count(a.id) as num,a.shop_id,c.shop_name,c.market_name,c.market_id')
            ->where($where)
            ->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })
            ->group('a.shop_id')
            ->order('c.market_id')
            ->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['date'] = $start_time;
            $data[$value['shop_id']]['shop_id'] = $value['shop_id'];
            $data[$value['shop_id']]['bh_store'] = $value['num'];
        }
        $where = array_merge($baseWhere,[['b.customer_setting_id_type','in',$dd]]);
        $res = Db::name('customer')->alias('a')
            ->join('customer_scar b','a.id = b.customer_id','left')
            ->join('shop c','a.shop_id = c.shop_id','left')
            ->field('count(a.id) as num,a.shop_id,c.shop_name,c.market_name,c.market_id')
            ->where($where)
            ->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })
            ->group('a.shop_id')
            ->order('c.market_id')
            ->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['date'] = $start_time;
            $data[$value['shop_id']]['shop_id'] = $value['shop_id'];
            $data[$value['shop_id']]['dd_store'] = $value['num'];
        }
        $where = array_merge($baseWhere,[['b.customer_setting_id_type','in',$xm]]);
        $res = Db::name('customer')->alias('a')
            ->join('customer_scar b','a.id = b.customer_id','left')
            ->join('shop c','a.shop_id = c.shop_id','left')
            ->field('count(a.id) as num,a.shop_id,c.shop_name,c.market_name,c.market_id')
            ->where($where)
            ->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })
            ->group('a.shop_id')
            ->order('c.market_id')
            ->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['date'] = $start_time;
            $data[$value['shop_id']]['shop_id'] = $value['shop_id'];
            $data[$value['shop_id']]['xm_store'] = $value['num'];
        }


        //体验数
        $where = [];
        array_push($where,['b.goods_id','=',168]);
        array_push($where,['c.customer_setting_id_type','in',$bh]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('customer_scar c','a.id = c.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(b.customer_id)) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['bh_receive']=$value['num'];
        }

        $where = [];
        array_push($where,['b.goods_id','=',150]);
        array_push($where,['c.customer_setting_id_type','in',$dd]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('customer_scar c','a.id = c.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(b.customer_id)) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['dd_receive']=$value['num'];
        }

        $where = [];
        array_push($where,['b.goods_id','=',165]);
        array_push($where,['c.customer_setting_id_type','in',$xm]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('customer_scar c','a.id = c.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(b.customer_id)) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['xm_receive']=$value['num'];
        }

        //体验顾客成交数
        $where = [];
        array_push($where,['b.goods_id','=',168]);
        array_push($where,['a.cj_money','>',500]);
        array_push($where,['d.customer_setting_id_type','in',$bh]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            // ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['bh_receive_deal']=$value['num'];
        }

        $where = [];
        array_push($where,['b.goods_id','=',150]);
        array_push($where,['a.cj_money','>',500]);
        array_push($where,['d.customer_setting_id_type','in',$dd]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            // ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['dd_receive_deal']=$value['num'];
        }

        $where = [];
        array_push($where,['b.goods_id','=',165]);
        array_push($where,['a.cj_money','>',500]);
        array_push($where,['d.customer_setting_id_type','in',$xm]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            // ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['xm_receive_deal']=$value['num'];
        }

        //体验金额
        $where = [];
        array_push($where,['b.goods_id','=',168]);
        array_push($where,['d.customer_setting_id_type','in',$bh]);
        array_push($where,['c.business_type','=',1]);
        array_push($where,['c.status','=',2]);
        array_push($where,['c.extra_type','=',0]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['bh_receive_money']=$value['num'];
        }
        $where = [];
        array_push($where,['b.goods_id','=',150]);
        array_push($where,['d.customer_setting_id_type','in',$dd]);
        array_push($where,['c.business_type','=',1]);
        array_push($where,['c.status','=',2]);
        array_push($where,['c.extra_type','=',1]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['dd_receive_money']=$value['num'];
        }

        $where = [];
        array_push($where,['b.goods_id','=',165]);
        array_push($where,['d.customer_setting_id_type','in',$xm]);
        array_push($where,['c.business_type','=',2]);
        array_push($where,['c.status','=',2]);
        // array_push($where,['c.extra_type','=',0]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['xm_receive_money']=$value['num'];
        }

        //直接进店人数
        $where = [];
        array_push($where,['b.goods_id','not in',[168,165,150]]);
        array_push($where,['a.cj_money','>',500]);
        array_push($where,['d.customer_setting_id_type','in',$bh]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            // ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['bh_direct']=$value['num'];
        }
        $where = [];
        array_push($where,['b.goods_id','not in',[168,165,150]]);
        array_push($where,['a.cj_money','>',500]);
        array_push($where,['d.customer_setting_id_type','in',$dd]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            // ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['dd_direct']=$value['num'];
        }
        $where = [];
        array_push($where,['b.goods_id','not in',[168,165,150]]);
        array_push($where,['a.cj_money','>',500]);
        array_push($where,['d.customer_setting_id_type','in',$xm]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            // ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['xm_direct']=$value['num'];
        }
        //直接进店金额
        $where = [];
        array_push($where,['b.goods_id','not in',[168,165,150]]);
        array_push($where,['d.customer_setting_id_type','in',$bh]);
        array_push($where,['c.business_type','=',1]);
        array_push($where,['c.status','=',2]);
        array_push($where,['c.extra_type','=',0]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['bh_direct_money']=$value['num'];
        }
        $where = [];
        array_push($where,['b.goods_id','not in',[168,165,150]]);
        array_push($where,['d.customer_setting_id_type','in',$dd]);
        array_push($where,['c.business_type','=',1]);
        array_push($where,['c.status','=',2]);
        array_push($where,['c.extra_type','=',1]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['dd_direct_money']=$value['num'];
        }

        $where = [];
        array_push($where,['b.goods_id','not in',[168,165,150]]);
        array_push($where,['d.customer_setting_id_type','in',$xm]);
        array_push($where,['c.business_type','=',2]);
        array_push($where,['c.status','=',2]);
        array_push($where,['c.extra_type','=',0]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        $res = Db::name('customer')->alias('a')
            ->join('service_log b','a.id = b.customer_id','left')
            ->join('shop_refund_order c','a.id = c.uid')
            ->join('customer_scar d','a.id = d.customer_id','left')
            ->where($where)->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
        foreach($res as $value)
        {
            $data[$value['shop_id']]['xm_direct_money']=$value['num'];
        }
        foreach($data as $key => $value)
        {
            if(empty($value['bh_store']))
            {
                $data[$key]['bh_store']=0;
            }
            if(empty($value['dd_store']))
            {
                $data[$key]['dd_store']=0;
            }
            if(empty($value['xm_store']))
            {
                $data[$key]['xm_store']=0;
            }
            if(empty($value['bh_receive']))
            {
                $data[$key]['bh_receive']=0;
            }
            if(empty($value['dd_receive']))
            {
                $data[$key]['dd_receive']=0;
            }
            if(empty($value['xm_receive']))
            {
                $data[$key]['xm_receive']=0;
            }
            if(empty($value['bh_receive_deal']))
            {
                $data[$key]['bh_receive_deal']=0;
            }
            if(empty($value['dd_receive_deal']))
            {
                $data[$key]['dd_receive_deal']=0;
            }
            if(empty($value['xm_receive_deal']))
            {
                $data[$key]['xm_receive_deal']=0;
            }
            if(empty($value['bh_receive_money']))
            {
                $data[$key]['bh_receive_money']=0;
            }
            if(empty($value['dd_receive_money']))
            {
                $data[$key]['dd_receive_money']=0;
            }
            if(empty($value['xm_receive_money']))
            {
                $data[$key]['xm_receive_money']=0;
            }
            if(empty($value['bh_direct']))
            {
                $data[$key]['bh_direct']=0;
            }
            if(empty($value['dd_direct']))
            {
                $data[$key]['dd_direct']=0;
            }
            if(empty($value['xm_direct']))
            {
                $data[$key]['xm_direct']=0;
            }
            if(empty($value['bh_direct_money']))
            {
                $data[$key]['bh_direct_money']=0;
            }
            if(empty($value['dd_direct_money']))
            {
                $data[$key]['dd_direct_money']=0;
            }
            if(empty($value['xm_direct_money']))
            {
                $data[$key]['xm_direct_money']=0;
            }
            $data[$key]['store_sum']=$data[$key]['bh_store']+$data[$key]['dd_store']+$data[$key]['xm_store'];
            $data[$key]['receive_sum']=$data[$key]['bh_receive']+$data[$key]['dd_receive']+$data[$key]['xm_receive'];
            $data[$key]['receive_deal_sum']=$data[$key]['bh_receive_deal']+$data[$key]['dd_receive_deal']+$data[$key]['xm_receive_deal'];
            $data[$key]['receive_money_sum']=$data[$key]['bh_receive_money']+$data[$key]['dd_receive_money']+$data[$key]['xm_receive_money'];
            $data[$key]['direct_sum']=$data[$key]['bh_direct']+$data[$key]['dd_direct']+$data[$key]['xm_direct'];
            $data[$key]['direct_money_sum']=$data[$key]['bh_direct_money']+$data[$key]['dd_direct_money']+$data[$key]['xm_direct_money'];
            krsort($data[$key]);
        }
        if($now == $date)
        {
            $data = array_merge($data,[]);
            Db::name('shop_customer_analyse')->insertAll($data);
        }else{
            $result = CustomerAnalyseModel::where('date','=',strtotime($date))->column('id','shop_id');
            foreach ($data as $key => $value)
            {
                if(!empty($result[$key]))
                    $data[$key]['id']=$result[$key];
            }
            $data = array_merge($data,[]);
            $model = new CustomerAnalyseModel;
            $model->saveAll($data);

        }
        return true;
    }

    public function setCustomerAnalyseControl()
    {
        $start = strtotime('-2 month');
        $end = strtotime('-1 day');
        while($start<=$end)
        {
            $this->setCustomerAnalyse(date('Y-m-d',$start));
            $start+=24*60*60;
        }
    }

    public function updateLoginType()
    {

        $where = [];

        array_push($where,['type','in',[1,3]]);
        array_push($where,['shop_id','<>','74076159037951']);
        array_push($where,['status','=','1']);

        $shop_list = DB::name('shop')->where($where)->column('shop_id');

        $where = [];

        array_push($where,['status','=',3]);
        array_push($where,['leave_at','>',"2024-05-01"]);
        array_push($where,['shop_id','in',$shop_list]);

        $leave_person = Db::name('shop_person')->where($where)->column('id');

        $customer = Db::name('customer')->where('nurse_id','in',$leave_person)->column('shop_id');

        $shop_ids = array_unique($customer);

        $where = [];

        array_push($where,['shop_id','in',$shop_ids]);
        array_push($where,['status','=',1]);
        array_push($where,['station_id','=',13]);

        $zl = Db::name('shop_person')->where($where)->column('id');

        foreach ($zl as $key => $value) {

            Db::name('shop_person')->where('id','=',$value)->update(['$status' => 2]);

        }

    }


	// 凌晨执行
	public function execute()
	{
		$this->customer_tj(); // 统计每日截至当前时间成交个数，保有个数，流失预警，流失个数数据

		$this->setOrderGoodsAnalyse(); //执行每天品项分析数据报表

		// $this->setCustomerAnalyseControl(); //执行每天客户分析数据报表

		$this->updateLoginType(); // 执行每天查询门店是否有离职员工

		// $model = new SendMsgModel();

  //       $model->everydaytask();

		return resultArray(['data'=>[],'error'=>'处理成功']);
		// $this->set_ceshi();
	}

	// 凌晨执行  --郑州太原市场
	public function setztmaktingyc()
	{
		$this->setCustomerZTYuCun();  //郑州太原市场

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}

	// 凌晨执行
	public function setkmxianmaktingyc()
	{
		$this->setCustomerKXYuCun(); //昆明西安市场

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}


    // 凌晨执行 东北市场
	public function setdjmaktingyc()
	{
		$this->setCustomerDJYuCun(); //执行新增门店的客户预存数据--2023-05-11

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}

	// 凌晨执行 川渝市场
	public function setcdcqmaktingyc()
	{
		$this->setCustomerCYYuCun();

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}

	// 凌晨执行 济南石家庄市场
	public function setjsmaktingyc()
	{
		$this->setCustomerJSYuCun();

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}


	// 凌晨执行 郑州直管+成都2家 +烟台
	public function setzgtmaktingyc()
	{
		$this->setCustomerZCYYuCun();

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}

	// 凌晨执行 北京+烟青潍市场
	public function setjmbjmaktingyc()
	{
		$this->setCustomerBJYYuCun();

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}


	// 凌晨执行 北京+烟青潍市场
	public function setzxunmaktingyc()
	{
		$this->setCustomerZHUXUNYuCun();

		return resultArray(['data'=>[],'error'=>'处理成功']);
	}

    //测
    public function send_msg(){

        $model = new SendUrlModel();

        $url = "https://api.weixin.qq.com/cgi-bin/token";

        // 公众号
        $jsonData = [

            'grant_type' => 'client_credential',

            'appid'      => 'wx7cde54d2bb9607e6',

            'secret'     => '1aa86183eca8d6ebf854cbc0349543df',

        ];

        $data = $model->send_url($url,$jsonData);

        $res = json_decode($data,true);

        $openid = 'orXbIs5Il9x5cC9wT_kP-GzS29Wk';

        $token = $res['access_token'];

        $posturl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$token;
        $status = 1;
        $dt = array(
            "touser" => $openid,
            'template_id'  => '-WYqE4OtQ07sxXa3RNwg8dnmKpKIM5ykX1cDGBtsACA',
            'url'   => "",
            'miniprogram' => array(
                'appid' => '',
                'pagepath' => '',
            ),
            'data' => array(
                'character_string4' => array('value' => '12312312323'),
                'time2' =>array('value' => date('Y-m-d H:i:s')),
                'thing10' =>array('value' => '张三'),
                'thing3' =>array('value' => '郑州店'),
                'amount1' =>array('value' => 100),
            ),
        );


        $postjson = json_encode($dt);

        // echo $postjson;

        // exit;
        $resder = $this->http_curl($posturl,'post','json',$postjson);

         var_dump($resder);
    }

    /**
     * 发送请求
     */
    public function http_curl($url,$type,$res,$arr)
    {
        /**
         * $url 请求的url
         * $type 请求类型
         * $res 返回数据类型
         * $arr post请求参数
         */
        $ch=curl_init();

        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if($type=='post'){
            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
        }
        $output = curl_exec($ch);
        curl_close($ch);
        if($res=='json'){
            return json_decode($output,true);
        }

    }




    /**************************************************数字化赋能项目-需要跑的数据**********************************************************************/

    //凌晨执行  定时跑，门店的业绩 ----------新的业绩计算规则-9月份开始
    public function shop_yj(){
        $map =[
            ['status','=',1],
            ['type','<>','2']
        ];
        $mz_shop = DB::name('shop')->where($map)->where('shop_type','=',1)->field('shop_id,market_id')->select()->toArray();
        $mz_shop_id = array_column($mz_shop,'shop_id');


        $md_shop = DB::name('shop')->where($map)->where('shop_type','=',2)->field('shop_id,market_id')->select()->toArray();
        $md_shop_id = array_column($md_shop,'shop_id');


        $year = date("Y");  // 当前年份
        $month = date("n"); // 当前月份（无前导零）
        $month = 10;
        $daysInMonth = date('t', mktime(0, 0, 0, $month, 1, $year)); //当前月份最大天数

        $shopModel = new ShopModel();
        $month_str = $month<10?'0'.$month:$month;
        for($i=1;$i<=24;$i++){
            $day_str = $i<10?'0'.$i:$i;
            $startTime = strtotime($year.'-'.$month.'-'.$i);

            $endTime = strtotime($year.'-'.$month.'-'.$i." 23:59:59");
            /*****门诊 begin*****/
            $mzXDMoneyAllOne = $shopModel->outpatientPerform($mz_shop_id,1,$startTime,$endTime); //门诊新单业绩

            $mzBDMoneyAllTwo = $shopModel->outpatientPerform($mz_shop_id,2,$startTime,$endTime); //门诊补单业绩
            $outpatient_shi = $shopModel->OutpatientActualPerform($mz_shop_id,$startTime,$endTime);//门诊实收业绩
            $outpatient_zhuan = $shopModel->OutpatientReferralPerform($mz_shop_id,$startTime,$endTime); //门诊转诊业绩
            $mzBHProject = $shopModel->outpatientPersformProject($mz_shop_id,$startTime,$endTime,1); //门诊疤痕业绩
            $mzPFXMProject = $shopModel->outpatientPersformProject($mz_shop_id,$startTime,$endTime,2,2); //门诊皮肤项目业绩
            $mzSTXMProject = $shopModel->outpatientPersformProject($mz_shop_id,$startTime,$endTime,2,1); //门诊身体项目业绩
            $mzQCDProject = $shopModel->outpatientPersformProject($mz_shop_id,$startTime,$endTime,3); //门诊青春痘业绩
            $mzHFPProject = $shopModel->outpatientPersformProject($mz_shop_id,$startTime,$endTime,4); //门诊护肤品业绩


            $mz_insert_all = $md_insert_all = [];
            foreach($mz_shop as $key=>$v) {
                $shop_id = $v['shop_id'];
                $sepbdMoney = isset($mzBDMoneyAllTwo[$shop_id]) ? $mzBDMoneyAllTwo[$shop_id] : 0; //补单
                $sepxdMoney = isset($mzXDMoneyAllOne[$shop_id]) ? $mzXDMoneyAllOne[$shop_id] : 0; //新单
                $bh = isset($mzBHProject[$shop_id]) ? $mzBHProject[$shop_id] : 0; //疤痕
                $stxm = isset($mzSTXMProject[$shop_id]) ? $mzSTXMProject[$shop_id] : 0; //身体项目
                $pfxm = isset($mzPFXMProject[$shop_id]) ? $mzPFXMProject[$shop_id] : 0; //皮肤项目
                $qcd = isset($mzQCDProject[$shop_id]) ? $mzQCDProject[$shop_id] : 0; //青春痘
                $hfp = isset($mzHFPProject[$shop_id]) ? $mzHFPProject[$shop_id] : 0; //护肤品
                $shi = isset($outpatient_shi[$shop_id]) ? $outpatient_shi[$shop_id] : 0; //护肤品
                $zhuan =  isset($outpatient_zhuan[$shop_id]) ? $outpatient_zhuan[$shop_id] : 0; //护肤品
                $mz_insert = [
                    'market_id'=>$v['market_id'],
                    'shop_id'=>$v['shop_id'],
                    'shop_type'=>1,
                    'date' =>$year.$month_str.$day_str,
                    'ss_amount'=>$shi,
                    'zz_amount'=>$zhuan,
                    'bd_amount'=>$sepbdMoney,
                    'xd_amount'=>$sepxdMoney,
                    'bh_amount'=>$bh,
                    'stxm_amount'=>$stxm,
                    'pfxm_amount'=>$pfxm,
                    'qcd_amount'=>$qcd,
                    'hfp_amount'=>$hfp,
                    'create_time'=>date('Y-m-d H:i:s')
                ];
                array_push($mz_insert_all,$mz_insert);

            }
            /*****门诊 end*****/


            /*****门店 begin*****/
            $md_bdyeji = $shopModel->shopPerform($md_shop_id,2,$startTime,$endTime,0,0); //补单
            $md_xdyeji = $shopModel->shopPerform($md_shop_id,1,$startTime,$endTime,0,0); //新单
            $shop_shi = $shopModel->ShopActualPerform($md_shop_id,$startTime,$endTime);//门店实收业绩
            $shop_zhuan = $shopModel->shopReferralPerform($md_shop_id,$startTime,$endTime); //门店转诊业绩
            $shopBHProject = $shopModel->shopPerform($md_shop_id,0,$startTime,$endTime,1); //门店疤痕业绩
            $shopPFXMProject = $shopModel->shopPerform($md_shop_id,0,$startTime,$endTime,2,2); //门店皮肤项目业绩
            $shopSTXMProject = $shopModel->shopPerform($md_shop_id,0,$startTime,$endTime,2,1); //门店身体项目业绩
            $shopQCDProject = $shopModel->shopPerform($md_shop_id,0,$startTime,$endTime,3); //门店青春痘业绩
            $shopHFPProject = $shopModel->shopPerform($md_shop_id,0,$startTime,$endTime,4); //门店护肤品业绩

            foreach($md_shop as $key=>$v) {
                $shop_id = $v['shop_id'];
                $md_insert = [
                    'market_id'=>$v['market_id'],
                    'shop_id'=>$v['shop_id'],
                    'shop_type'=>2,
                    'date' =>$year.$month_str.$day_str,
                    'ss_amount'=> isset($shop_shi[$shop_id]) ? $shop_shi[$shop_id] : 0,
                    'zz_amount'=>isset($shop_zhuan[$shop_id]) ? $shop_zhuan[$shop_id] : 0,
                    'bd_amount'=>isset($md_bdyeji[$shop_id]) ? $md_bdyeji[$shop_id] : 0,
                    'xd_amount'=>isset($md_xdyeji[$shop_id]) ? $md_xdyeji[$shop_id] : 0,
                    'bh_amount'=>isset($shopBHProject[$shop_id]) ? $shopBHProject[$shop_id] : 0,
                    'stxm_amount'=>isset($shopSTXMProject[$shop_id]) ? $shopSTXMProject[$shop_id] : 0,
                    'pfxm_amount'=>isset($shopPFXMProject[$shop_id]) ? $shopPFXMProject[$shop_id] : 0,
                    'qcd_amount'=>isset($shopQCDProject[$shop_id]) ? $shopQCDProject[$shop_id] : 0,
                    'hfp_amount'=>isset($shopHFPProject[$shop_id]) ? $shopHFPProject[$shop_id] : 0,
                    'create_time'=>date('Y-m-d H:i:s')
                ];
                array_push($md_insert_all,$md_insert);
            }
            DB::name('shop_performance_log')->insertAll($mz_insert_all);
            DB::name('shop_performance_log')->insertAll($md_insert_all);
            /*****门店 end*****/
        }
    }

    //凌晨执行，门店门诊定时的业绩----------旧的业绩计算规则
    public function md_mz_yj(){
        $map =[
            ['status','=',1],
            ['type','<>','2']
        ];
        $mz_shop = DB::name('shop')->where($map)->where('shop_type','=',1)->field('shop_id as shopId,market_id as marketId')->select()->toArray();
        $mz_shop_id = array_column($mz_shop,'shop_id');


        $md_shop = DB::name('shop')->where($map)->where('shop_type','=',2)->field('shop_id as shopId,market_id as marketId')->select()->toArray();
        $md_shop_id = array_column($md_shop,'shopId');

        $year = date("Y");  // 当前年份
        $month = date("n"); // 当前月份（无前导零）
        $month = 7;
        $daysInMonth = date('t', mktime(0, 0, 0, $month, 1, $year)); //当前月份最大天数

        $shopModel = new ShopModel();
        $month_str = $month<10?'0'.$month:$month;
        for($i=1;$i<=$daysInMonth;$i++){
            $day_str = $i<10?'0'.$i:$i;
            $startTime = strtotime($year.'-'.$month.'-'.$i); //开始时间
            $endTime = strtotime($year.'-'.$month.'-'.$i." 23:59:59"); //结束时间
            $md_insert_all =  $mz_insert_all = [];

             $amountAll =$shopModel->amountMoneyAllAll($startTime,$endTime); //实收
             $scarMoneyAll =$shopModel->sumShopPayMoneyNewMZAll('Bh',$startTime,$endTime); //疤痕
             $projectMoneyAll =$shopModel->sumShopPayMoneyNewMZAll('XM',$startTime,$endTime); //项目
             $projectStMoneyAll = $shopModel->sumShopPayMoneyNewMZAll('STXM',$startTime,$endTime); //身体项目
             $projectPfMoneyAll = $shopModel->sumShopPayMoneyNewMZAll('PFXM',$startTime,$endTime); //皮肤项目
             $qcdMoneyAll =$shopModel->sumShopPayMoneyNewMZAll('QCD',$startTime,$endTime); // 青春痘
             $hfpMoneyAll =$shopModel->sumShopPayMoneyNewMZAll('HFP',$startTime,$endTime); // 护肤品
             //$referralMoneyAllOne =$shopModel->referralMoneyAll(1,$startTime,$endTime);
             //$referralMoneyAllTwo =$shopModel->referralMoneyAll(2,$startTime,$endTime);
             $scarMoneyAllOne =$shopModel->sumShopPayMoneyNewAll('Bh',1,$startTime,$endTime);
             $projectMoneyAllOne =$shopModel->sumShopPayMoneyNewAll('XM',1,$startTime,$endTime);
             $projectStMoneyAllOne = $shopModel->sumShopPayMoneyNewAll('STXM',1,$startTime,$endTime); //身体项目
             $projectPfMoneyAllOne = $shopModel->sumShopPayMoneyNewAll('PFXM',1,$startTime,$endTime); //皮肤项目
             $qcdMoneyAllOne =$shopModel->sumShopPayMoneyNewAll('QCD',1,$startTime,$endTime); //青春痘
             $hfpMoneyAllOne =$shopModel->sumShopPayMoneyNewAll('HFP',1,$startTime,$endTime);//护肤品


             //门诊
            foreach($mz_shop as $k=>$v){
                 //实收金额业绩计算
                 $amount = empty($amountAll[$v['shopId']])?0:$amountAll[$v['shopId']];

                 //转诊金额计算  川渝市场和门诊的转诊  都是 默认 0 不计算 对接财务确定；2022-07-24
                 if($v['marketId'] == 8 || $v['marketId'] == 9 || $v['marketId'] == 10|| $v['marketId'] == 11  ){
                     //$referralMoney =0;
                     //疤痕业绩计算--川渝市场
                     $scarMoney = empty($scarMoneyAll[$v['shopId']])?0:$scarMoneyAll[$v['shopId']];// 疤痕
                     $projectMoney = empty($projectMoneyAll[$v['shopId']])?0:$projectMoneyAll[$v['shopId']];// 项目
                     $projectStMoney = empty($projectStMoneyAll[$v['shopId']])?0:$projectStMoneyAll[$v['shopId']];// 身体项目
                     $projectPfMoney = empty($projectPfMoneyAll[$v['shopId']])?0:$projectPfMoneyAll[$v['shopId']];// 皮肤项目
                     $qcdMoney = empty($qcdMoneyAll[$v['shopId']])?0:$qcdMoneyAll[$v['shopId']];// 青春痘
                     $hfpMoney = empty($hfpMoneyAll[$v['shopId']])?0:$hfpMoneyAll[$v['shopId']];// 护肤品

                     $newsXDMoney = $this->sumShopPayMoneyNewMZ('XD',$v['shopId'],1,$startTime,$endTime); //新单
                     $budanMoney = $this->sumShopPayMoneyNewMZ('BD',$v['shopId'],1,$startTime,$endTime); //补单

                 }else{

                     //$referralMoney = empty($referralMoneyAllOne[$value['shopId']])?0:$referralMoneyAllOne[$value['shopId']]; //原来的转诊业绩
                     $scarMoney = empty($scarMoneyAllOne[$v['shopId']])?0:$scarMoneyAllOne[$v['shopId']]; //疤痕
                     $projectMoney = empty($projectMoneyAllOne[$v['shopId']])?0:$projectMoneyAllOne[$v['shopId']];//项目
                     $projectStMoney = empty($projectStMoneyAllOne[$v['shopId']])?0:$projectStMoneyAllOne[$v['shopId']];// 身体项目
                     $projectPfMoney = empty($projectPfMoneyAllOne[$v['shopId']])?0:$projectPfMoneyAllOne[$v['shopId']];// 皮肤项目
                     $qcdMoney = empty($qcdMoneyAllOne[$v['shopId']])?0:$qcdMoneyAllOne[$v['shopId']];// 青春痘
                     $hfpMoney = empty($hfpMoneyAllOne[$v['shopId']])?0:$hfpMoneyAllOne[$v['shopId']];// 护肤品

                     $newsXDMoney = $this->sumShopPayMoneyNew('XD',$v['shopId'],1,$startTime,$endTime); //新单

                     $budanMoney = $this->sumShopPayMoneyNew('BD', $v['shopId'],1,$startTime,$endTime); //补单
                 }



                 //转诊业绩 新的计算规则
                 $bhoxmAmount = bcadd($scarMoney,$projectMoney,2); //疤痕+项目业绩合计
                 $qcdohfpAmount = bcadd($qcdMoney,$hfpMoney,2); //青春痘+护肤品业绩合计
                 $bohtotalAmount = bcadd($bhoxmAmount,$qcdohfpAmount,2);
                 $referralMoney = bcsub($bohtotalAmount,$amount,2); //疤痕+项目+护肤品+青春痘  减去 实收金额

                $shop_id = $v['shopId'];
                $mz_insert = [
                    'market_id'=>$v['marketId'],
                    'shop_id'=>$shop_id,
                    'shop_type'=>1,
                    'date' =>$year.$month_str.$day_str,
                    'ss_amount'=> $amount,
                    'zz_amount'=>$referralMoney,
                    'bd_amount'=>$budanMoney,
                    'xd_amount'=>$newsXDMoney,
                    'bh_amount'=>$scarMoney,
                    'xm_amount'=>$projectMoney,
                    'stxm_amount'=>$projectStMoney,
                    'pfxm_amount'=>$projectPfMoney,
                    'qcd_amount'=>$qcdMoney,
                    'hfp_amount'=>$hfpMoney,
                    'create_time'=>date('Y-m-d H:i:s')
                ];
                array_push($mz_insert_all,$mz_insert);

            }
            DB::name('shop_performance_log')->insertAll($mz_insert_all);

//            $scarMoneyAllTwo =$shopModel->sumShopPayMoneyNewAll('Bh',2,$startTime,$endTime);
//            $projectMoneyAllTwo =$shopModel->sumShopPayMoneyNewAll('XM',2,$startTime,$endTime);
//            $projectStMoneyAllTwo = $shopModel->sumShopPayMoneyNewAll('STXM',2,$startTime,$endTime); //身体项目
//            $projectPfMoneyAllTwo = $shopModel->sumShopPayMoneyNewAll('PFXM',2,$startTime,$endTime); //皮肤项目
//            $qcdMoneyAllTwo =$shopModel->sumShopPayMoneyNewAll('QCD',2,$startTime,$endTime);
//            $hfpMoneyAllTwo =$shopModel->sumShopPayMoneyNewAll('HFP',2,$startTime,$endTime);
//
//
//            //门店
//            foreach($md_shop as $key=>$v){
//                //实收金额业绩计算
//                $amount = empty($amountAll[$v['shopId']])?0:$amountAll[$v['shopId']];
//                //转诊金额计算  川渝市场和门诊的转诊  都是 默认 0 不计算 对接财务确定；2022-07-24
//                if($v['marketId'] == 8 || $v['marketId'] == 9 || $v['marketId'] == 10|| $v['marketId'] == 11  ){
//                    //$referralMoney =0;
//                    //疤痕业绩计算--川渝市场
//                    $scarMoney = empty($scarMoneyAll[$v['shopId']])?0:$scarMoneyAll[$v['shopId']];// 疤痕
//                    $projectMoney = empty($projectMoneyAll[$v['shopId']])?0:$projectMoneyAll[$v['shopId']];// 项目
//                    $projectStMoney = empty($projectStMoneyAll[$v['shopId']])?0:$projectStMoneyAll[$v['shopId']];// 身体项目
//                    $projectPfMoney = empty($projectPfMoneyAll[$v['shopId']])?0:$projectPfMoneyAll[$v['shopId']];// 皮肤项目
//                    $qcdMoney = empty($qcdMoneyAll[$v['shopId']])?0:$qcdMoneyAll[$v['shopId']];// 青春痘
//                    $hfpMoney = empty($hfpMoneyAll[$v['shopId']])?0:$hfpMoneyAll[$v['shopId']];// 护肤品
//
//                    $newsXDMoney = $this->sumShopPayMoneyNewMZ('XD',$v['shopId'],2,$startTime,$endTime); //新单
//                    $budanMoney = $this->sumShopPayMoneyNewMZ('BD',$v['shopId'],2,$startTime,$endTime); //补单
//                }else{
//                    // $referralMoney =$this->referralMoney($value['shopId'],$value['shop_type'],$startTime,$endTime);
//
//                    //$referralMoney = empty($referralMoneyAllTwo[$value['shopId']])?0:$referralMoneyAllTwo[$value['shopId']]; //原来的转诊业绩
//                    $scarMoney = empty($scarMoneyAllTwo[$v['shopId']])?0:$scarMoneyAllTwo[$v['shopId']]; //疤痕
//                    $projectMoney = empty($projectMoneyAllTwo[$v['shopId']])?0:$projectMoneyAllTwo[$v['shopId']];//项目
//                    $projectStMoney = empty($projectStMoneyAllTwo[$v['shopId']])?0:$projectStMoneyAllTwo[$v['shopId']];// 身体项目
//                    $projectPfMoney = empty($projectPfMoneyAllTwo[$v['shopId']])?0:$projectPfMoneyAllTwo[$v['shopId']];// 皮肤项目
//                    $qcdMoney = empty($qcdMoneyAllTwo[$v['shopId']])?0:$qcdMoneyAllTwo[$v['shopId']];// 青春痘
//                    $hfpMoney = empty($hfpMoneyAllTwo[$v['shopId']])?0:$hfpMoneyAllTwo[$v['shopId']];// 护肤品
//                    $newsXDMoney = $this->sumShopPayMoneyNew('XD',$v['shopId'],2,$startTime,$endTime); //新单
//                    $budanMoney = $this->sumShopPayMoneyNew('BD', $v['shopId'],2,$startTime,$endTime); //补单
//
//                }
//
//                //转诊业绩 新的计算规则
//                $bhoxmAmount = bcadd($scarMoney,$projectMoney,2); //疤痕+项目业绩合计
//                $qcdohfpAmount = bcadd($qcdMoney,$hfpMoney,2); //青春痘+护肤品业绩合计
//                $bohtotalAmount = bcadd($bhoxmAmount,$qcdohfpAmount,2);
//                $referralMoney = bcsub($bohtotalAmount,$amount,2); //疤痕+项目+护肤品+青春痘  减去 实收金额
//
//                $shop_id = $v['shopId'];
//                $md_insert = [
//                    'market_id'=>$v['marketId'],
//                    'shop_id'=>$shop_id,
//                    'shop_type'=>2,
//                    'date' =>$year.$month_str.$day_str,
//                    'ss_amount'=> $amount,
//                    'zz_amount'=>$referralMoney,
//                    'bd_amount'=>$budanMoney,
//                    'xd_amount'=>$newsXDMoney,
//                    'bh_amount'=>$scarMoney,
//                    'xm_amount'=>$projectMoney,
//                    'stxm_amount'=>$projectStMoney,
//                    'pfxm_amount'=>$projectPfMoney,
//                    'qcd_amount'=>$qcdMoney,
//                    'hfp_amount'=>$hfpMoney,
//                    'create_time'=>date('Y-m-d H:i:s')
//                ];
//                array_push($md_insert_all,$md_insert);
//            }
//            DB::name('shop_performance_log')->insertAll($md_insert_all);

        }

    }

    //凌晨执行，客户门诊消费金额-需要跑的数据
    public function mz_customer_consume(){
        list($md_shop,$insert_today,$model,$today,$end_day) = $this->public_where();
        $map =[
            ['status','=',1],
            ['type','<>','2'],
        ];
        $mz_shop = DB::name('shop')->where($map)->where('shop_type','=',1)->field('shop_id,market_id')->select()->toArray();

        $begin_time = strtotime($today);
        $ymd = date('Ymd',$begin_time);
        foreach($mz_shop as $kk=>$vv) {
            $error_customer = [];
            $md_insert_all =  [];
            $shop_id = $vv['shop_id'];
            $market_id = $vv['market_id'];
            $map = [
                ['shop_id', '=', $shop_id],
            ];
            $customer_id = DB::name('customer')->where($map)->field('id,member_classification,consumption,telephone')->select()->toArray();
            $customer_id = array_column($customer_id, null, 'id');
            $where = [
                ['status', '=', 2],
                ['shop_id', '=', $shop_id],
                ['type', '=', 3],
                ['refund_type', '=', '101.02'],
                ['deal_time', '=', $begin_time],
            ];
            $shoukuan = DB::name('shop_refund_order')->where($where)->field('sum(pay_amount) as total_amount,uid')->group('uid')->select()->toArray();
            $shoukuan_uids = array_column($shoukuan, 'uid');
            $shoukuan = array_column($shoukuan, 'total_amount', 'uid');

            $where = [
                ['status', '=', 2],
                ['shop_id', '=', $shop_id],
                ['type', '=', 1],
                ['refund_type', '<>', '101.03'],
                ['deal_time', '=', $begin_time],
            ];
            $tuikuan = DB::name('shop_refund_order')->where($where)->field('sum(pay_amount) as total_amount,uid')->group('uid')->select()->toArray();
            $tuikuan_uids = array_column($tuikuan, 'uid');
            $tuikuan = array_column($tuikuan, 'total_amount', 'uid');

            $where = [
                ['status', '=', 2],
                ['shop_id', '=', $shop_id],
                ['type', '=', 2],
                ['deal_time', '=', $begin_time],
            ];
            $tuihuo = DB::name('shop_refund_order')->where($where)->field('sum(total_amount) as total_amount,uid')->group('uid')->select()->toArray();
            $tuihuo_uids = array_column($tuihuo, 'uid');
            $tuihuo = array_column($tuihuo, 'total_amount', 'uid');

            $where = [
                ['status', '=', 2],
                ['shop_id', '=', $shop_id],
                ['deal_time', '=', $begin_time],
            ];
            $chuhuo = DB::name('shop_order')->where($where)->field('sum(order_amount) as total_amount,uid')->group('uid')->select()->toArray();
            $chuhuo_uids = array_column($chuhuo, 'uid');
            $chuhuo = array_column($chuhuo, 'total_amount', 'uid');

            $uids = array_merge($shoukuan_uids, $tuikuan_uids, $tuihuo_uids, $chuhuo_uids);
            $uids = array_unique($uids);


            foreach ($uids as $key => $val) {
                $shoukuan_money = isset($shoukuan[$val]) ? $shoukuan[$val] : 0;
                $tuikuan_money = isset($tuikuan[$val]) ? $tuikuan[$val] : 0;
                $chuhuo_money = isset($chuhuo[$val]) ? $chuhuo[$val] : 0;
                $tuihuo_money = isset($tuihuo[$val]) ? $tuihuo[$val] : 0;
                $consumption_sum = bcsub($shoukuan_money, $tuikuan_money, 2); //当天的累计消费金额
                $insert = [
                    'market_id' => $market_id,
                    'shop_id' => $shop_id,
                    'date' => $ymd,
                    'customer_id' => $val,
                    'level' => 0,
                    'collection_amount' => $shoukuan_money,
                    'refund_amount' => $tuikuan_money,
                    'shipment_amount' => $chuhuo_money,
                    'return_goods_amount' => $tuihuo_money,
                    'consumption_sum' => $consumption_sum,
                    'create_time' => date('Y-m-d H:i:s'),
                    'shop_type'=>1,
                ];

                if (isset($customer_id[$val])) {
                    $consumption = $customer_id[$val]['consumption']; //客户累计消费金额-customer 里边的
                    $phone = $customer_id[$val]['telephone'];
                    $insert['customer_level'] = $customer_id[$val]['member_classification'];
                    $insert['customer_phone'] = $phone;
                    $insert['customer_consumption'] = $consumption;
                } else {
                    array_push($error_customer, $val);
                    $customer_data = DB::name('customer')->where('id', $val)->field('id,member_classification,consumption,telephone')->find();
                    $insert['customer_level'] = '';
                    $insert['customer_phone'] = '';
                    $insert['customer_consumption'] = '';
                    if (!empty($customer_data)) {
                        $insert['customer_level'] = $customer_data['member_classification'];
                        $insert['customer_phone'] = $customer_data['telephone'];
                        $insert['customer_consumption'] = $customer_data['consumption'];
                    }
                }
                array_push($md_insert_all, $insert);
            }

            DB::name('customer_consumption_log')->insertAll($md_insert_all);
        }
        var_dump($error_customer);



    }

    //凌晨执行，客户门店-消费金额-需要跑的数据 市场id 4,6,8,9
    public function md_customer_consume(){
        list($md_shop,$insert_today,$model,$today,$end_day) = $this->public_where();
        //第一批是太原市场  4
        //第二批是郑州市场 6
        //第四批是重庆市场 8
        //第五批是成都市场  9
        $map =[
            ['status','=',1],
            ['type','<>','2'],
            ['market_id','in',[4,6,8,9]]
        ];
        $md_shop = DB::name('shop')->where($map)->where('shop_type','=',2)->field('shop_id,market_id')->select()->toArray();

        $begin_time = strtotime($today);
        $ymd = date('Ymd',$begin_time);
        foreach($md_shop as $kk=>$vv) {
            $error_customer = [];
            $md_insert_all =  [];
            $shop_id = $vv['shop_id'];
            $market_id = $vv['market_id'];
            $map = [
                ['shop_id', '=', $shop_id],
            ];
            $customer_id = DB::name('customer')->where($map)->field('id,member_classification,consumption,telephone')->select()->toArray();
            $customer_id = array_column($customer_id, null, 'id');
            $where = [
                ['status', '=', 2],
                ['shop_id', '=', $shop_id],
                ['type', '=', 3],
                ['refund_type', '=', '101.02'],
                ['deal_time', '=', $begin_time],
            ];
            $shoukuan = DB::name('shop_refund_order')->where($where)->field('sum(pay_amount) as total_amount,uid')->group('uid')->select()->toArray();
            $shoukuan_uids = array_column($shoukuan, 'uid');
            $shoukuan = array_column($shoukuan, 'total_amount', 'uid');

            $where = [
                ['status', '=', 2],
                ['shop_id', '=', $shop_id],
                ['type', '=', 1],
                ['refund_type', '<>', '101.03'],
                ['deal_time', '=', $begin_time],
            ];
            $tuikuan = DB::name('shop_refund_order')->where($where)->field('sum(pay_amount) as total_amount,uid')->group('uid')->select()->toArray();
            $tuikuan_uids = array_column($tuikuan, 'uid');
            $tuikuan = array_column($tuikuan, 'total_amount', 'uid');

            $where = [
                ['status', '=', 2],
                ['shop_id', '=', $shop_id],
                ['type', '=', 2],
                ['deal_time', '=', $begin_time],
            ];
            $tuihuo = DB::name('shop_refund_order')->where($where)->field('sum(total_amount) as total_amount,uid')->group('uid')->select()->toArray();
            $tuihuo_uids = array_column($tuihuo, 'uid');
            $tuihuo = array_column($tuihuo, 'total_amount', 'uid');

            $where = [
                ['status', '=', 2],
                ['shop_id', '=', $shop_id],
                ['deal_time', '=', $begin_time],
            ];
            $chuhuo = DB::name('shop_order')->where($where)->field('sum(order_amount) as total_amount,uid')->group('uid')->select()->toArray();
            $chuhuo_uids = array_column($chuhuo, 'uid');
            $chuhuo = array_column($chuhuo, 'total_amount', 'uid');

            $uids = array_merge($shoukuan_uids, $tuikuan_uids, $tuihuo_uids, $chuhuo_uids);
            $uids = array_unique($uids);

            foreach ($uids as $key => $val) {
                $shoukuan_money = isset($shoukuan[$val]) ? $shoukuan[$val] : 0;
                $tuikuan_money = isset($tuikuan[$val]) ? $tuikuan[$val] : 0;
                $chuhuo_money = isset($chuhuo[$val]) ? $chuhuo[$val] : 0;
                $tuihuo_money = isset($tuihuo[$val]) ? $tuihuo[$val] : 0;
                $consumption_sum = bcsub($shoukuan_money, $tuikuan_money, 2); //当天的累计消费金额
                $insert = [
                    'market_id' => $market_id,
                    'shop_id' => $shop_id,
                    'date' => $ymd,
                    'customer_id' => $val,
                    'level' => 0,
                    'collection_amount' => $shoukuan_money,
                    'refund_amount' => $tuikuan_money,
                    'shipment_amount' => $chuhuo_money,
                    'return_goods_amount' => $tuihuo_money,
                    'consumption_sum' => $consumption_sum,
                    'create_time' => date('Y-m-d H:i:s'),
                    'shop_type'=>2,
                ];

                if (isset($customer_id[$val])) {
                    $consumption = $customer_id[$val]['consumption']; //客户累计消费金额-customer 里边的
                    $phone = $customer_id[$val]['telephone'];
                    $insert['customer_level'] = $customer_id[$val]['member_classification'];
                    $insert['customer_phone'] = $phone;
                    $insert['customer_consumption'] = $consumption;
                } else {
                    array_push($error_customer, $val);
                    $customer_data = DB::name('customer')->where('id', $val)->field('id,member_classification,consumption,telephone')->find();
                    $insert['customer_level'] = '';
                    $insert['customer_phone'] = '';
                    $insert['customer_consumption'] = '';
                    if (!empty($customer_data)) {
                        $insert['customer_level'] = $customer_data['member_classification'];
                        $insert['customer_phone'] = $customer_data['telephone'];
                        $insert['customer_consumption'] = $customer_data['consumption'];
                    }
                }
                array_push($md_insert_all, $insert);
            }

            DB::name('customer_consumption_log')->insertAll($md_insert_all);
        }
        var_dump($error_customer);

    }

    //凌晨执行，客户门店-消费金额-需要跑的数据 市场id 12-16、19
    public function md_one_customer_consume(){
        list($md_shop,$insert_today,$model,$today,$end_day) = $this->public_where();

        //第六批是天津市场  12
        //第七批是沈阳市场  13
        //第八批是哈尔滨市场  15
        //第九批是长春市场  14
        //第十批是昆明市场  16
        //第十一批是西安市场  19

        $map =[
            ['status','=',1],
            ['type','<>','2'],
            ['market_id','in',[12,13,14,15,16,19]]
        ];
        $md_shop = DB::name('shop')->where($map)->where('shop_type','=',2)->field('shop_id,market_id')->select()->toArray();
        $begin_time = strtotime($today);
        $ymd = date('Ymd',$begin_time);
        foreach($md_shop as $kk=>$vv) {
            $error_customer = [];
            $md_insert_all =  [];
            $shop_id = $vv['shop_id'];
            $market_id = $vv['market_id'];
            $map = [
                ['shop_id', '=', $shop_id],
            ];
            $customer_id = DB::name('customer')->where($map)->field('id,member_classification,consumption,telephone')->select()->toArray();
            $customer_id = array_column($customer_id, null, 'id');
            $where = [
                ['status', '=', 2],
                ['shop_id', '=', $shop_id],
                ['type', '=', 3],
                ['refund_type', '=', '101.02'],
                ['deal_time', '=', $begin_time],
            ];
            $shoukuan = DB::name('shop_refund_order')->where($where)->field('sum(pay_amount) as total_amount,uid')->group('uid')->select()->toArray();
            $shoukuan_uids = array_column($shoukuan, 'uid');
            $shoukuan = array_column($shoukuan, 'total_amount', 'uid');

            $where = [
                ['status', '=', 2],
                ['shop_id', '=', $shop_id],
                ['type', '=', 1],
                ['refund_type', '<>', '101.03'],
                ['deal_time', '=', $begin_time],
            ];
            $tuikuan = DB::name('shop_refund_order')->where($where)->field('sum(pay_amount) as total_amount,uid')->group('uid')->select()->toArray();
            $tuikuan_uids = array_column($tuikuan, 'uid');
            $tuikuan = array_column($tuikuan, 'total_amount', 'uid');

            $where = [
                ['status', '=', 2],
                ['shop_id', '=', $shop_id],
                ['type', '=', 2],
                ['deal_time', '=', $begin_time],
            ];
            $tuihuo = DB::name('shop_refund_order')->where($where)->field('sum(total_amount) as total_amount,uid')->group('uid')->select()->toArray();
            $tuihuo_uids = array_column($tuihuo, 'uid');
            $tuihuo = array_column($tuihuo, 'total_amount', 'uid');

            $where = [
                ['status', '=', 2],
                ['shop_id', '=', $shop_id],
                ['deal_time', '=', $begin_time],
            ];
            $chuhuo = DB::name('shop_order')->where($where)->field('sum(order_amount) as total_amount,uid')->group('uid')->select()->toArray();
            $chuhuo_uids = array_column($chuhuo, 'uid');
            $chuhuo = array_column($chuhuo, 'total_amount', 'uid');

            $uids = array_merge($shoukuan_uids, $tuikuan_uids, $tuihuo_uids, $chuhuo_uids);
            $uids = array_unique($uids);

            foreach ($uids as $key => $val) {
                $shoukuan_money = isset($shoukuan[$val]) ? $shoukuan[$val] : 0;
                $tuikuan_money = isset($tuikuan[$val]) ? $tuikuan[$val] : 0;
                $chuhuo_money = isset($chuhuo[$val]) ? $chuhuo[$val] : 0;
                $tuihuo_money = isset($tuihuo[$val]) ? $tuihuo[$val] : 0;
                $consumption_sum = bcsub($shoukuan_money, $tuikuan_money, 2); //当天的累计消费金额
                $insert = [
                    'market_id' => $market_id,
                    'shop_id' => $shop_id,
                    'date' => $ymd,
                    'customer_id' => $val,
                    'level' => 0,
                    'collection_amount' => $shoukuan_money,
                    'refund_amount' => $tuikuan_money,
                    'shipment_amount' => $chuhuo_money,
                    'return_goods_amount' => $tuihuo_money,
                    'consumption_sum' => $consumption_sum,
                    'create_time' => date('Y-m-d H:i:s'),
                    'shop_type'=>2,
                ];

                if (isset($customer_id[$val])) {
                    $consumption = $customer_id[$val]['consumption']; //客户累计消费金额-customer 里边的
                    $phone = $customer_id[$val]['telephone'];
                    $insert['customer_level'] = $customer_id[$val]['member_classification'];
                    $insert['customer_phone'] = $phone;
                    $insert['customer_consumption'] = $consumption;
                } else {
                    array_push($error_customer, $val);
                    $customer_data = DB::name('customer')->where('id', $val)->field('id,member_classification,consumption,telephone')->find();
                    $insert['customer_level'] = '';
                    $insert['customer_phone'] = '';
                    $insert['customer_consumption'] = '';
                    if (!empty($customer_data)) {
                        $insert['customer_level'] = $customer_data['member_classification'];
                        $insert['customer_phone'] = $customer_data['telephone'];
                        $insert['customer_consumption'] = $customer_data['consumption'];
                    }
                }
                array_push($md_insert_all, $insert);
            }

            DB::name('customer_consumption_log')->insertAll($md_insert_all);
        }
        var_dump($error_customer);

    }

    //凌晨执行，客户门店-消费金额-需要跑的数据 市场id 21,23,25,94,99,101,102,103,105
    public function md_two_customer_consume(){
        list($md_shop,$insert_today,$model,$today,$end_day) = $this->public_where();

        //第十二批是济南市场  21
        //第十三批是石家庄市场  23
        //第十四批是北京市场  25
        //第三批是郑州万达市场 94
        //第十五批是郑州公园茂市场 99
        //第十五批是金水市场   101
        //第十五批是三全市场  102
        //第十五批是郑东商业中心  103
        //第十五批是重庆光环市场  105
        $map =[
            ['status','=',1],
            ['type','<>','2'],
            ['market_id','in',[21,23,25,94,99,101,102,103,105]]
        ];
        $md_shop = DB::name('shop')->where($map)->where('shop_type','=',2)->field('shop_id,market_id')->select()->toArray();
        $begin_time = strtotime($today);
        $ymd = date('Ymd',$begin_time);
        foreach($md_shop as $kk=>$vv) {
            $error_customer = [];
            $md_insert_all =  [];
            $shop_id = $vv['shop_id'];
            $market_id = $vv['market_id'];
            $map = [
                ['shop_id', '=', $shop_id],
            ];
            $customer_id = DB::name('customer')->where($map)->field('id,member_classification,consumption,telephone')->select()->toArray();
            $customer_id = array_column($customer_id, null, 'id');
            $where = [
                ['status', '=', 2],
                ['shop_id', '=', $shop_id],
                ['type', '=', 3],
                ['refund_type', '=', '101.02'],
                ['deal_time', '=', $begin_time],
            ];
            $shoukuan = DB::name('shop_refund_order')->where($where)->field('sum(pay_amount) as total_amount,uid')->group('uid')->select()->toArray();
            $shoukuan_uids = array_column($shoukuan, 'uid');
            $shoukuan = array_column($shoukuan, 'total_amount', 'uid');

            $where = [
                ['status', '=', 2],
                ['shop_id', '=', $shop_id],
                ['type', '=', 1],
                ['refund_type', '<>', '101.03'],
                ['deal_time', '=', $begin_time],
            ];
            $tuikuan = DB::name('shop_refund_order')->where($where)->field('sum(pay_amount) as total_amount,uid')->group('uid')->select()->toArray();
            $tuikuan_uids = array_column($tuikuan, 'uid');
            $tuikuan = array_column($tuikuan, 'total_amount', 'uid');

            $where = [
                ['status', '=', 2],
                ['shop_id', '=', $shop_id],
                ['type', '=', 2],
                ['deal_time', '=', $begin_time],
            ];
            $tuihuo = DB::name('shop_refund_order')->where($where)->field('sum(total_amount) as total_amount,uid')->group('uid')->select()->toArray();
            $tuihuo_uids = array_column($tuihuo, 'uid');
            $tuihuo = array_column($tuihuo, 'total_amount', 'uid');

            $where = [
                ['status', '=', 2],
                ['shop_id', '=', $shop_id],
                ['deal_time', '=', $begin_time],
            ];
            $chuhuo = DB::name('shop_order')->where($where)->field('sum(order_amount) as total_amount,uid')->group('uid')->select()->toArray();
            $chuhuo_uids = array_column($chuhuo, 'uid');
            $chuhuo = array_column($chuhuo, 'total_amount', 'uid');

            $uids = array_merge($shoukuan_uids, $tuikuan_uids, $tuihuo_uids, $chuhuo_uids);
            $uids = array_unique($uids);

            foreach ($uids as $key => $val) {
                $shoukuan_money = isset($shoukuan[$val]) ? $shoukuan[$val] : 0;
                $tuikuan_money = isset($tuikuan[$val]) ? $tuikuan[$val] : 0;
                $chuhuo_money = isset($chuhuo[$val]) ? $chuhuo[$val] : 0;
                $tuihuo_money = isset($tuihuo[$val]) ? $tuihuo[$val] : 0;
                $consumption_sum = bcsub($shoukuan_money, $tuikuan_money, 2); //当天的累计消费金额
                $insert = [
                    'market_id' => $market_id,
                    'shop_id' => $shop_id,
                    'date' => $ymd,
                    'customer_id' => $val,
                    'level' => 0,
                    'collection_amount' => $shoukuan_money,
                    'refund_amount' => $tuikuan_money,
                    'shipment_amount' => $chuhuo_money,
                    'return_goods_amount' => $tuihuo_money,
                    'consumption_sum' => $consumption_sum,
                    'create_time' => date('Y-m-d H:i:s'),
                    'shop_type'=>2,
                ];

                if (isset($customer_id[$val])) {
                    $consumption = $customer_id[$val]['consumption']; //客户累计消费金额-customer 里边的
                    $phone = $customer_id[$val]['telephone'];
                    $insert['customer_level'] = $customer_id[$val]['member_classification'];
                    $insert['customer_phone'] = $phone;
                    $insert['customer_consumption'] = $consumption;
                } else {
                    array_push($error_customer, $val);
                    $customer_data = DB::name('customer')->where('id', $val)->field('id,member_classification,consumption,telephone')->find();
                    $insert['customer_level'] = '';
                    $insert['customer_phone'] = '';
                    $insert['customer_consumption'] = '';
                    if (!empty($customer_data)) {
                        $insert['customer_level'] = $customer_data['member_classification'];
                        $insert['customer_phone'] = $customer_data['telephone'];
                        $insert['customer_consumption'] = $customer_data['consumption'];
                    }
                }
                array_push($md_insert_all, $insert);
            }

            DB::name('customer_consumption_log')->insertAll($md_insert_all);
        }
        var_dump($error_customer);

    }



    //公共条件
    public function public_where(){
        $map =[
            ['status','=',1],
            ['type','<>','2'],
        ];
        $md_shop = DB::name('shop')->where($map)->where('shop_type','=',2)->field('shop_id,market_id')->select()->toArray();

        $insert_today = date('Ymd', strtotime("-1 day")); //所有累计保有流失数据全部跑的是前一天
        $model = new ReserveandLost();
        $today = date('Y-m-d', strtotime("-1 day"));
        $end_day = strtotime($today . " 23:59:59");

        return [$md_shop,$insert_today,$model,$today,$end_day];
    }

    //A类顾客累计-需要跑的数据-仅限门店
    public function aclass_total(){

        list($md_shop,$insert_today,$model,$today,$end_day) = $this->public_where();

        $md_aclass_total = [];
        //门店 累计保有-累计流失
        foreach ($md_shop as $k => $vv) {
            $public_map = [
                ['shop_id', '=', $vv['shop_id']],
                ['member_classification', '=', 73]
            ];
            $md_map = [];
            array_push($md_map, ['cj_money', '>=', 500]);
            array_push($md_map, ['cj_time', '>', 0]);
            array_push($md_map, ['cj_time', '<=', $end_day]);
            $lj_cj_customer = DB::name('customer')->where($public_map)->where($md_map)->column('id'); //A类成交顾客

            $lost_caseIds = $model->lost_case($lj_cj_customer, $today);
            $lost_caseIds_num = count($lost_caseIds);
            $lj_cjCustomerIds = array_diff($lj_cj_customer, $lost_caseIds); //最终成交的顾客id

            $lj_cjCustomerIds_count = count($lj_cjCustomerIds);
            $baoyou_ls = $this->baoyou_customer($lj_cjCustomerIds, $today,$vv['shop_id']); //获取累计保有以及流失人数

            $baoyou = $baoyou_ls['by'];
            $ljby_count = count($baoyou); //累计保有人数

            $lost = $baoyou_ls['ls'];
            $ljls_count = count($baoyou_ls['ls']);//累计流失人数

            $ljby_rete = $lj_cjCustomerIds_count > 0 ? bcmul(bcdiv($ljby_count, $lj_cjCustomerIds_count, 4), 100, 2) : 0;  //累计保有率
            $ljls_rete = $lj_cjCustomerIds_count > 0 ? bcmul(bcdiv($ljls_count, $lj_cjCustomerIds_count, 4), 100, 2) : 0;  //累计流失率

            $aclass_total_install = [
                'market_id' => $vv['market_id'],
                'shop_id' => $vv['shop_id'],
                'shop_type' => 2,
                'date' => $insert_today,
                'ls_ya_customer_num' => $lost_caseIds_num,
                'ls_ya_customer_id' => empty($lost_caseIds) ? '' : implode(',', $lost_caseIds),
                'finally_cj_customer_num' => $lj_cjCustomerIds_count,
                'by_total_num' => $ljby_count,
                'by_total_customer_id' => empty($baoyou) ? '' : implode(',', $baoyou),
                'by_total_rate' => $ljby_rete,
                'ls_total_num' => $ljls_count,
                'ls_total_customer_id' => empty($lost) ? '' : implode(',', $lost),
                'ls_total_rate' => $ljls_rete,
                'create_time' => date('Y-m-d H:i:s')
            ];
            array_push($md_aclass_total, $aclass_total_install);
        }
        $res = DB::name('aclass_total_log')->insertAll($md_aclass_total);
        if($res){
            echo "处理完成";
        }else{
            echo "处理失败";
        }
    }
    /*
     * A类顾客周期性-需要跑的数据
     */
    public function aclass_periodicity(){
        list($md_shop,$insert_today,$model,$today,$end_day) = $this->public_where();

        $md_aclass_zq = [];

        foreach ($md_shop as $k => $vv) {
            $public_map = [
                ['shop_id', '=', $vv['shop_id']],
                ['member_classification', '=', 73]
            ];
            $md_map =[];
            $start_day = strtotime("-1 years",$end_day);
            array_push($md_map, ['cj_money', '>=', 500]);
            array_push($md_map, ['cj_time', '>', 0]);
            array_push($md_map,['cj_time','between',"$start_day,$end_day"]);
            $zqx_cj_customer = DB::name('customer')->where($public_map)->where($md_map)->column('id'); //a类成交顾客
            $lost_caseIds = $model->lost_case($zqx_cj_customer,$today);
            $lost_caseIds_num = count($lost_caseIds);
            $zqx_cjCustomerIds = array_diff($zqx_cj_customer,$lost_caseIds); //最终成交的顾客id
            $zqx_cjCustomerIds_count  = count($zqx_cjCustomerIds);
            $baoyou_ls = $this->baoyou_customer($zqx_cjCustomerIds,$today,$vv['shop_id']); //获取周期性保有以及流失人数

            $baoyou  = $baoyou_ls['by'];
            $zqxby_count = count($baoyou_ls['by']);//周期性保有人数

            $lost = $baoyou_ls['ls'];
            $zqxls_count = count($baoyou_ls['ls']);//周期性流失人数

            $zqxby_rete = $zqx_cjCustomerIds_count > 0 ? bcmul(bcdiv($zqxby_count,$zqx_cjCustomerIds_count,4),100,2):0; //周期性保有率
            $zqxls_rete = $zqx_cjCustomerIds_count > 0 ? bcmul(bcdiv($zqxls_count,$zqx_cjCustomerIds_count,4),100,2):0; //周期性流失率

            $aclass_zq_install = [
                'market_id'=>$vv['market_id'],
                'shop_id'=>$vv['shop_id'],
                'shop_type'=>2,
                'date' =>$insert_today,

                'ls_ya_customer_num' => $lost_caseIds_num,
                'ls_ya_customer_id' => empty($lost_caseIds) ? '' : implode(',', $lost_caseIds),
                'finally_cj_customer_num' => $zqx_cjCustomerIds_count,

                'by_periodicityl_num'=> $zqxby_count,
                'by_periodicity_customer_id'=>empty($baoyou)?'':implode(',',$baoyou),
                'by_periodicity_rate'=>$zqxby_rete,
                'ls_periodicity_num'=>$zqxls_count,
                'ls_periodicity_customer_id'=>empty($lost)?'':implode(',',$lost),
                'ls_periodicity_rate'=>$zqxls_rete,
                'create_time'=>date('Y-m-d H:i:s')
            ];
            array_push($md_aclass_zq,$aclass_zq_install);
        }

        $res =DB::name('aclass_periodicity_log')->insertAll($md_aclass_zq);
        if($res){
            echo "处理完成";
        }else{
            echo "处理失败";
        }
    }

    //b类顾客累计-需要跑的数据
    public function bclass_total(){
        list($md_shop,$insert_today,$model,$today,$end_day) = $this->public_where();

        $md_bclass_total = [];
        //门店 累计保有-累计流失
        foreach($md_shop as $k=>$vv){
            $public_map = [
                ['shop_id','=',$vv['shop_id']],
                ['member_classification','=',72]
            ];
            $md_map =[];
            array_push($md_map, ['cj_money', '>=', 500]);
            array_push($md_map, ['cj_time', '>', 0]);
            array_push($md_map,['cj_time','<=',$end_day]);
            $lj_cj_customer = DB::name('customer')->where($public_map)->where($md_map)->column('id'); //B类成交顾客

            $lost_caseIds = $model->lost_case($lj_cj_customer,$today);
            $lost_caseIds_num = count($lost_caseIds);  //流失优案 客户数

            $lj_cjCustomerIds = array_diff($lj_cj_customer,$lost_caseIds); //最终成交的顾客id
            $lj_cjCustomerIds_count  = count($lj_cjCustomerIds);

            $baoyou_ls = $this->baoyou_customer($lj_cjCustomerIds,$today,$vv['shop_id']); //获取累计保有以及流失人数

            $baoyou  = $baoyou_ls['by'];
            $ljby_count = count($baoyou); //累计保有人数

            $lost = $baoyou_ls['ls'];
            $ljls_count = count($baoyou_ls['ls']);//累计流失人数

            $ljby_rete = $lj_cjCustomerIds_count > 0 ? bcmul(bcdiv($ljby_count,$lj_cjCustomerIds_count,4),100,2):0;  //累计保有率
            $ljls_rete = $lj_cjCustomerIds_count > 0 ? bcmul(bcdiv($ljls_count,$lj_cjCustomerIds_count,4),100,2):0;  //累计流失率

            $bclass_total_install = [
                'market_id'=>$vv['market_id'],
                'shop_id'=>$vv['shop_id'],
                'shop_type'=>2,
                'date' =>$insert_today,
                'ls_ya_customer_num' => $lost_caseIds_num,
                'ls_ya_customer_id' => empty($lost_caseIds) ? '' : implode(',', $lost_caseIds),
                'finally_cj_customer_num' => $lj_cjCustomerIds_count,
                'by_total_num'=> $ljby_count,
                'by_total_customer_id'=>empty($baoyou)?'':implode(',',$baoyou),
                'by_total_rate'=>$ljby_rete,
                'ls_total_num'=>$ljls_count,
                'ls_total_customer_id'=>empty($lost)?'':implode(',',$lost),
                'ls_total_rate'=>$ljls_rete,
                'create_time'=>date('Y-m-d H:i:s')
            ];
            array_push($md_bclass_total,$bclass_total_install);
        }
        $res = DB::name('bclass_total_log')->insertAll($md_bclass_total);
        if($res){
            echo "处理完成";
        }else{
            echo "处理失败";
        }
    }
    /*
     * b类顾客周期性-需要跑的数据
     */
    public function bclass_periodicity(){
        list($md_shop,$insert_today,$model,$today,$end_day) = $this->public_where();

        $md_bclass_zq = [];
        //门店 累计保有-累计流失
        foreach($md_shop as $k=>$vv){
            $public_map = [
                ['shop_id','=',$vv['shop_id']],
                ['member_classification','=',72]
            ];
            $md_map =[];
            $start_day = strtotime("-1 years",$end_day);
            array_push($md_map, ['cj_money', '>=', 500]);
            array_push($md_map, ['cj_time', '>', 0]);
            array_push($md_map,['cj_time','between',"$start_day,$end_day"]);
            $zqx_cj_customer = DB::name('customer')->where($public_map)->where($md_map)->column('id'); //b类成交顾客

            $lost_caseIds = $model->lost_case($zqx_cj_customer,$today);
            $lost_caseIds_num = count($lost_caseIds);
            $zqx_cjCustomerIds = array_diff($zqx_cj_customer,$lost_caseIds); //最终成交的顾客id
            $zqx_cjCustomerIds_count  = count($zqx_cjCustomerIds);
            $baoyou_ls = $this->baoyou_customer($zqx_cjCustomerIds,$today,$vv['shop_id']); //获取周期性保有以及流失人数

            $baoyou  = $baoyou_ls['by'];
            $zqxby_count = count($baoyou_ls['by']);//周期性保有人数

            $lost = $baoyou_ls['ls'];
            $zqxls_count = count($baoyou_ls['ls']);//周期性流失人数

            $zqxby_rete = $zqx_cjCustomerIds_count > 0 ? bcmul(bcdiv($zqxby_count,$zqx_cjCustomerIds_count,4),100,2):0; //周期性保有率
            $zqxls_rete = $zqx_cjCustomerIds_count > 0 ? bcmul(bcdiv($zqxls_count,$zqx_cjCustomerIds_count,4),100,2):0; //周期性流失率

            $bclass_zq_install = [
                'market_id'=>$vv['market_id'],
                'shop_id'=>$vv['shop_id'],
                'shop_type'=>2,
                'date' =>$insert_today,
                'ls_ya_customer_num' => $lost_caseIds_num,
                'ls_ya_customer_id' => empty($lost_caseIds) ? '' : implode(',', $lost_caseIds),
                'finally_cj_customer_num' => $zqx_cjCustomerIds_count,
                'finally_cj_customer_id' => empty($zqx_cjCustomerIds) ? '' : implode(',', $zqx_cjCustomerIds),
                'by_periodicityl_num'=> $zqxby_count,
                'by_periodicity_customer_id'=>empty($baoyou)?'':implode(',',$baoyou),
                'by_periodicity_rate'=>$zqxby_rete,
                'ls_periodicity_num'=>$zqxls_count,
                'ls_periodicity_customer_id'=>empty($lost)?'':implode(',',$lost),
                'ls_periodicity_rate'=>$zqxls_rete,
                'create_time'=>date('Y-m-d H:i:s')
            ];
            array_push($md_bclass_zq,$bclass_zq_install);
        }
        $res = DB::name('bclass_periodicity_log')->insertAll($md_bclass_zq);
        if($res){
            echo "处理完成";
        }else{
            echo "处理失败";
        }
    }

    /*
     * 门店周期性-需要跑的数据
     */
    public function shop_periodicity(){
        list($md_shop,$insert_today,$model,$today,$end_day) = $this->public_where();
        $md_periodicity  = [];
        //门店 周期性保有-累计流失
        foreach($md_shop as $k=>$vv) {
            $md_map = [
                ['shop_id', '=', $vv['shop_id']]
            ];
            $start_day = strtotime("-1 years", $end_day);
            array_push($md_map, ['cj_money', '>=', 500]);
            array_push($md_map, ['cj_time', '>', 0]);
            array_push($md_map, ['cj_time', 'between', "$start_day,$end_day"]);

            $zqx_cj_customer = DB::name('customer')->where($md_map)->column('id');

            $lost_caseIds = $model->lost_case($zqx_cj_customer, $today);
            $lost_caseIds_num = count($lost_caseIds);

            $zqx_cjCustomerIds = array_diff($zqx_cj_customer, $lost_caseIds); //最终成交的顾客id

            $zqx_cjCustomerIds_count = count($zqx_cjCustomerIds);
            $baoyou_ls = $this->baoyou_customer($zqx_cjCustomerIds, $today, $vv['shop_id']); //获取周期性保有以及流失人数

            $baoyou = $baoyou_ls['by'];
            $zqxby_count = count($baoyou_ls['by']);//周期性保有人数

            $lost = $baoyou_ls['ls'];
            $zqxls_count = count($baoyou_ls['ls']);//周期性流失人数

            $zqxby_rete = $zqx_cjCustomerIds_count > 0 ? bcmul(bcdiv($zqxby_count, $zqx_cjCustomerIds_count, 4), 100, 2) : 0; //周期性保有率
            $zqxls_rete = $zqx_cjCustomerIds_count > 0 ? bcmul(bcdiv($zqxls_count, $zqx_cjCustomerIds_count, 4), 100, 2) : 0; //周期性流失率

            $md_zq_install = [
                'market_id' => $vv['market_id'],
                'shop_id' => $vv['shop_id'],
                'shop_type' => 2,
                'date' => $insert_today,

                'ls_ya_customer_num' => $lost_caseIds_num,
                'ls_ya_customer_id' => empty($lost_caseIds) ? '' : implode(',', $lost_caseIds),
                'finally_cj_customer_num' => $zqx_cjCustomerIds_count,

                'by_periodicity_num' => $zqxby_count,
                'by_periodicity_customer_id' => empty($baoyou) ? '' : implode(',', $baoyou),
                'by_periodicity_rate' => $zqxby_rete,
                'ls_periodicity_num' => $zqxls_count,
                'ls_periodicity_customer_id' => empty($lost) ? '' : implode(',', $lost),
                'ls_periodicity_rate' => $zqxls_rete,
                'create_time' => date('Y-m-d H:i:s')
            ];
            array_push($md_periodicity, $md_zq_install);
        }
        $res =  DB::name('shop_periodicity_log')->insertAll($md_periodicity);
        if($res){
            echo "处理完成";
        }else{
            echo "处理失败";
        }
    }

    /*
     * 门店累计-需要跑的数据
     */
    public function shop_total(){
        list($md_shop,$insert_today,$model,$today,$end_day) = $this->public_where();
        $md_total = [];
        //门店 累计保有-累计流失
        foreach ($md_shop as $k => $vv) {
            $public_map = [
                ['shop_id', '=', $vv['shop_id']],
            ];
            $md_map = [];
            array_push($md_map, ['cj_money', '>=', 500]);
            array_push($md_map, ['cj_time', '>', 0]);
            array_push($md_map, ['cj_time', '<=', $end_day]);
            $lj_cj_customer = DB::name('customer')->where($public_map)->where($md_map)->column('id'); //首次成交顾客id

            $lost_caseIds = $model->lost_case($lj_cj_customer, $today); //流失优案的客户id
            $lost_caseIds_num =  count($lost_caseIds);

            $lj_cjCustomerIds = array_diff($lj_cj_customer, $lost_caseIds); //最终成交的顾客id
            $lj_cjCustomerIds_count = count($lj_cjCustomerIds);

            $baoyou_ls = $this->baoyou_customer($lj_cjCustomerIds, $today,$vv['shop_id']); //获取累计保有以及流失人数

            $baoyou = $baoyou_ls['by'];
            $ljby_count = count($baoyou); //累计保有人数

            $lost = $baoyou_ls['ls'];
            $ljls_count = count($baoyou_ls['ls']);//累计流失人数

            $ljby_rete = $lj_cjCustomerIds_count > 0 ? bcmul(bcdiv($ljby_count, $lj_cjCustomerIds_count, 4), 100, 2) : 0;  //累计保有率
            $ljls_rete = $lj_cjCustomerIds_count > 0 ? bcmul(bcdiv($ljls_count, $lj_cjCustomerIds_count, 4), 100, 2) : 0;  //累计流失率

            $shop_total_install = [
                'market_id' => $vv['market_id'],
                'shop_id' => $vv['shop_id'],
                'shop_type' => 2,
                'date' => $insert_today,
                'ls_ya_customer_num' => $lost_caseIds_num,
                'ls_ya_customer_id' => empty($lost_caseIds) ? '' : implode(',', $lost_caseIds),
                'finally_cj_customer_num' => $lj_cjCustomerIds_count,
                'by_total_num' => $ljby_count,
                'by_total_customer_id' => empty($baoyou) ? '' : implode(',', $baoyou),
                'by_total_rate' => $ljby_rete,
                'ls_total_num' => $ljls_count,
                'ls_total_customer_id' => empty($lost) ? '' : implode(',', $lost),
                'ls_total_rate' => $ljls_rete,
                'create_time' => date('Y-m-d H:i:s')
            ];
            array_push($md_total, $shop_total_install);
        }
        $res = DB::name('shop_total_log')->insertAll($md_total);
        if($res){
            echo "处理完成";
        }else{
            echo "处理失败";
        }
    }


    //凌晨执行  定时跑，门店的业绩 ----------新的业绩计算规则-9月份开始
    public function shop_performance_new(){
        $map =[
            ['status','=',1],
            ['type','<>','2']
        ];
        $mz_shop = DB::name('shop')->where($map)->where('shop_type','=',1)->field('shop_id,market_id')->select()->toArray();
        $mz_shop_id = array_column($mz_shop,'shop_id');


        $md_shop = DB::name('shop')->where($map)->where('shop_type','=',2)->field('shop_id,market_id')->select()->toArray();
        $md_shop_id = array_column($md_shop,'shop_id');

        $insert_today = date('Ymd', strtotime("-1 day")); //所有累计保有流失数据全部跑的是前一天
        $shopModel = new ShopModel();
        $today = date('Y-m-d', strtotime("-1 day"));

        $shopModel = new ShopModel();

        $startTime = strtotime($today);
        $endTime = strtotime($today." 23:59:59");
        /*****门诊 begin*****/
        $mzXDMoneyAllOne = $shopModel->outpatientPerform($mz_shop_id,1,$startTime,$endTime); //门诊新单业绩

        $mzBDMoneyAllTwo = $shopModel->outpatientPerform($mz_shop_id,2,$startTime,$endTime); //门诊补单业绩
        $outpatient_shi = $shopModel->OutpatientActualPerform($mz_shop_id,$startTime,$endTime);//门诊实收业绩
        $outpatient_zhuan = $shopModel->OutpatientReferralPerform($mz_shop_id,$startTime,$endTime); //门诊转诊业绩
        $mzBHProject = $shopModel->outpatientPersformProject($mz_shop_id,$startTime,$endTime,1); //门诊疤痕业绩
        $mzPFXMProject = $shopModel->outpatientPersformProject($mz_shop_id,$startTime,$endTime,2,2); //门诊皮肤项目业绩
        $mzSTXMProject = $shopModel->outpatientPersformProject($mz_shop_id,$startTime,$endTime,2,1); //门诊身体项目业绩
        $mzQCDProject = $shopModel->outpatientPersformProject($mz_shop_id,$startTime,$endTime,3); //门诊青春痘业绩
        $mzHFPProject = $shopModel->outpatientPersformProject($mz_shop_id,$startTime,$endTime,4); //门诊护肤品业绩


        $mz_insert_all = $md_insert_all = [];
        foreach($mz_shop as $key=>$v) {
            $shop_id = $v['shop_id'];
            $sepbdMoney = isset($mzBDMoneyAllTwo[$shop_id]) ? $mzBDMoneyAllTwo[$shop_id] : 0; //补单
            $sepxdMoney = isset($mzXDMoneyAllOne[$shop_id]) ? $mzXDMoneyAllOne[$shop_id] : 0; //新单
            $bh = isset($mzBHProject[$shop_id]) ? $mzBHProject[$shop_id] : 0; //疤痕
            $stxm = isset($mzSTXMProject[$shop_id]) ? $mzSTXMProject[$shop_id] : 0; //身体项目
            $pfxm = isset($mzPFXMProject[$shop_id]) ? $mzPFXMProject[$shop_id] : 0; //皮肤项目
            $qcd = isset($mzQCDProject[$shop_id]) ? $mzQCDProject[$shop_id] : 0; //青春痘
            $hfp = isset($mzHFPProject[$shop_id]) ? $mzHFPProject[$shop_id] : 0; //护肤品
            $shi = isset($outpatient_shi[$shop_id]) ? $outpatient_shi[$shop_id] : 0; //护肤品
            $zhuan =  isset($outpatient_zhuan[$shop_id]) ? $outpatient_zhuan[$shop_id] : 0; //护肤品
            $mz_insert = [
                'market_id'=>$v['market_id'],
                'shop_id'=>$v['shop_id'],
                'shop_type'=>1,
                'date' =>$insert_today,
                'ss_amount'=>$shi,
                'zz_amount'=>$zhuan,
                'bd_amount'=>$sepbdMoney,
                'xd_amount'=>$sepxdMoney,
                'bh_amount'=>$bh,
                'stxm_amount'=>$stxm,
                'pfxm_amount'=>$pfxm,
                'qcd_amount'=>$qcd,
                'hfp_amount'=>$hfp,
                'create_time'=>date('Y-m-d H:i:s')
            ];
            array_push($mz_insert_all,$mz_insert);

        }
        DB::name('shop_performance_log')->insertAll($mz_insert_all);
        /*****门诊 end*****/


        /*****门店 begin*****/
        $md_bdyeji = $shopModel->shopPerform($md_shop_id,2,$startTime,$endTime,0,0); //补单
        $md_xdyeji = $shopModel->shopPerform($md_shop_id,1,$startTime,$endTime,0,0); //新单
        $shop_shi = $shopModel->ShopActualPerform($md_shop_id,$startTime,$endTime);//门店实收业绩
        $shop_zhuan = $shopModel->shopReferralPerform($md_shop_id,$startTime,$endTime); //门店转诊业绩
        $shopBHProject = $shopModel->shopPerform($md_shop_id,0,$startTime,$endTime,1); //门店疤痕业绩
        $shopPFXMProject = $shopModel->shopPerform($md_shop_id,0,$startTime,$endTime,2,2); //门店皮肤项目业绩
        $shopSTXMProject = $shopModel->shopPerform($md_shop_id,0,$startTime,$endTime,2,1); //门店身体项目业绩
        $shopQCDProject = $shopModel->shopPerform($md_shop_id,0,$startTime,$endTime,3); //门店青春痘业绩
        $shopHFPProject = $shopModel->shopPerform($md_shop_id,0,$startTime,$endTime,4); //门店护肤品业绩

        foreach($md_shop as $key=>$v) {
            $shop_id = $v['shop_id'];
            $md_insert = [
                'market_id'=>$v['market_id'],
                'shop_id'=>$v['shop_id'],
                'shop_type'=>2,
                'date' => $insert_today,
                'ss_amount'=> isset($shop_shi[$shop_id]) ? $shop_shi[$shop_id] : 0,
                'zz_amount'=>isset($shop_zhuan[$shop_id]) ? $shop_zhuan[$shop_id] : 0,
                'bd_amount'=>isset($md_bdyeji[$shop_id]) ? $md_bdyeji[$shop_id] : 0,
                'xd_amount'=>isset($md_xdyeji[$shop_id]) ? $md_xdyeji[$shop_id] : 0,
                'bh_amount'=>isset($shopBHProject[$shop_id]) ? $shopBHProject[$shop_id] : 0,
                'stxm_amount'=>isset($shopSTXMProject[$shop_id]) ? $shopSTXMProject[$shop_id] : 0,
                'pfxm_amount'=>isset($shopPFXMProject[$shop_id]) ? $shopPFXMProject[$shop_id] : 0,
                'qcd_amount'=>isset($shopQCDProject[$shop_id]) ? $shopQCDProject[$shop_id] : 0,
                'hfp_amount'=>isset($shopHFPProject[$shop_id]) ? $shopHFPProject[$shop_id] : 0,
                'create_time'=>date('Y-m-d H:i:s')
            ];
            array_push($md_insert_all,$md_insert);
        }
        DB::name('shop_performance_log')->insertAll($md_insert_all);
        /*****门店 end*****/

    }



    /**************************************************数字化赋能项目-需要跑的数据-end **********************************************************************/


    //A类顾客累计-周期性
    public function aclass_total_periodicity(){
        $map =[
            ['status','=',1],
            ['type','<>','2'],
            ['market_id','=',4]
        ];
        $md_shop = DB::name('shop')->where($map)->where('shop_type','=',2)->field('shop_id,market_id')->select()->toArray();

        $year = date("Y");  // 当前年份
        $month = date("n"); // 当前月份（无前导零）
        $month = 10;
        $month_str = $month<10?'0'.$month:$month;

        $daysInMonth = date('t', mktime(0, 0, 0, $month, 1, $year)); //当前月份最大天数
        $mz_bclass_total = $mz_bclass_zq = [];

        $model = new ReserveandLost();
        for($i=23;$i<=23;$i++) {
            $day_str = $i < 10 ? '0' . $i : $i;
            $mz_aclass_total = $mz_aclass_zq = [];
            $md_aclass_total = $md_aclass_zq = [];
            //门诊 累计保有-累计流失
//            foreach($mz_shop as $key=>$v){
//                $mz_where = $mz_map = [
//                    ['shop_id','=',$v['shop_id']],
//                    ['member_classification','=',72]
//                ];
//                array_push($mz_map,['final_consumption|final_service','>','0']);
//                array_push($mz_where,['final_consumption|final_service','>','0']);
//                $today = date($year.'-'.$month.'-'.$i);
//
//                $end_day = strtotime($today." 23:59:59");
//
//                array_push($mz_map,['cj_time','>',$end_day]);
//                $lj_cj_customer = DB::name('customer')->where($mz_map)->column('id'); //A类成交顾客
//                $lost_caseIds = $model->lost_case($lj_cj_customer,$today);
//                $lj_cjCustomerIds = array_diff($lj_cj_customer,$lost_caseIds); //最终成交的顾客id
//                $lj_cjCustomerIds_count  = count($lj_cjCustomerIds);
//                $baoyou = $model->baoyou_customer($lj_cjCustomerIds,$today);
//                $ljby_count = count($baoyou); //累计保有人数
//
//                $lost = $model->lost_customer($lj_cjCustomerIds,$today); //累计流失人数
//                $ljls_count = count($lost); //累计流失人数
//
//                $ljby_rete = bcsub(bcdiv($ljby_count,$lj_cjCustomerIds_count,4),100);  //累计保有率
//                $ljls_rete = bcsub(bcdiv($ljls_count,$lj_cjCustomerIds_count,4),100);  //累计流失率
//
//                $bclass_total_install = [
//                    'market_id'=>$v['market_id'],
//                    'shop_id'=>$v['shop_id'],
//                    'shop_type'=>2,
//                    'date' =>$year.$month_str.$day_str,
//                    'by_total_num'=> $ljby_count,
//                    'by_total_customer_id'=>iempty($baoyou)?'':implode(',',$baoyou),
//                    'by_total_rate'=>$ljby_rete,
//                    'ls_total_num'=>$ljls_count,
//                    'ls_total_customer_id'=>empty($lost)?'':implode(',',$lost),
//                    'ls_total_rate'=>$ljls_rete,
//                    'create_time'=>date('Y-m-d H:i:s')
//                ];
//                array_push($mz_bclass_total,$bclass_total_install);
//
//
//                $end_day = strtotime("-1 years",$end_day);
//                array_push($mz_map,['cj_time','>',$end_day]);
//                $zqx_cj_customer = DB::name('customer')->where($mz_map)->column('id'); //A类成交顾客
//                $lost_caseIds = $model->lost_case($zqx_cj_customer,$today);
//                $zqx_cjCustomerIds = array_diff($zqx_cj_customer,$lost_caseIds); //最终成交的顾客id
//                $zqx_cjCustomerIds_count  = count($zqx_cjCustomerIds);
//                $baoyou = $model->baoyou_customer($zqx_cjCustomerIds,$today);
//                $zqxby_count = count($baoyou); //周期性保有人数
//
//                $lost = $model->lost_customer($zqx_cjCustomerIds,$today); //周期性流失人数
//                $zqxls_count = count($lost); //周期性流失人数
//
//
//                $zqxby_rete = $zqx_cjCustomerIds_count > 0 ? bcsub(bcdiv($zqxby_count,$zqx_cjCustomerIds_count,4),100):0; //周期性保有率
//                $zqxls_rete = $zqx_cjCustomerIds_count > 0 ? bcsub(bcdiv($zqxls_count,$zqx_cjCustomerIds_count,4),100):0; //周期性流失率
//
//                $bclass_zq_install = [
//                    'market_id'=>$v['market_id'],
//                    'shop_id'=>$v['shop_id'],
//                    'shop_type'=>2,
//                    'date' =>$year.$month_str.$day_str,
//                    'by_periodicityl_num'=> $zqxby_count,
//                    'by_periodicity_customer_id'=>iempty($baoyou)?'':implode(',',$baoyou),
//                    'by_periodicity_rate'=>$zqxby_rete,
//                    'ls_periodicity_num'=>$zqxls_count,
//                    'ls_periodicity_customer_id'=>empty($lost)?'':implode(',',$lost),
//                    'ls_periodicity_rate'=>$zqxls_rete,
//                    'create_time'=>date('Y-m-d H:i:s')
//                ];
//                array_push($mz_bclass_zq,$bclass_zq_install);
//            }
            //门店 累计保有-累计流失
            foreach ($md_shop as $k => $vv) {
                $public_map = [
                    ['shop_id', '=', $vv['shop_id']],
                    ['member_classification', '=', 73]
                ];
                $today = date($year . '-' . $month . '-' . $i);
                $end_day = strtotime($today . " 23:59:59");
                $md_map = [];
                array_push($md_map, ['cj_money', '>=', 500]);
                array_push($md_map, ['cj_time', '>', 0]);
                array_push($md_map, ['cj_time', '<=', $end_day]);
                $lj_cj_customer = DB::name('customer')->where($public_map)->where($md_map)->column('id'); //b类成交顾客

                $lost_caseIds = $model->lost_case($lj_cj_customer, $today);
                $lost_caseIds_num = count($lost_caseIds);
                $lj_cjCustomerIds = array_diff($lj_cj_customer, $lost_caseIds); //最终成交的顾客id

                $lj_cjCustomerIds_count = count($lj_cjCustomerIds);
                $baoyou_ls = $this->baoyou_customer($lj_cjCustomerIds, $today,$vv['shop_id']); //获取累计保有以及流失人数

                $baoyou = $baoyou_ls['by'];
                $ljby_count = count($baoyou); //累计保有人数

                $lost = $baoyou_ls['ls'];
                $ljls_count = count($baoyou_ls['ls']);//累计流失人数

                $ljby_rete = $lj_cjCustomerIds_count > 0 ? bcmul(bcdiv($ljby_count, $lj_cjCustomerIds_count, 4), 100, 2) : 0;  //累计保有率
                $ljls_rete = $lj_cjCustomerIds_count > 0 ? bcmul(bcdiv($ljls_count, $lj_cjCustomerIds_count, 4), 100, 2) : 0;  //累计流失率

                $aclass_total_install = [
                    'market_id' => $vv['market_id'],
                    'shop_id' => $vv['shop_id'],
                    'shop_type' => 2,
                    'date' => $year . $month_str . $day_str,

                    'ls_ya_customer_num' => $lost_caseIds_num,
                    'ls_ya_customer_id' => empty($lost_caseIds) ? '' : implode(',', $lost_caseIds),
                    'finally_cj_customer_num' => $lj_cjCustomerIds_count,
                    'by_total_num' => $ljby_count,
                    'by_total_customer_id' => empty($baoyou) ? '' : implode(',', $baoyou),
                    'by_total_rate' => $ljby_rete,
                    'ls_total_num' => $ljls_count,
                    'ls_total_customer_id' => empty($lost) ? '' : implode(',', $lost),
                    'ls_total_rate' => $ljls_rete,
                    'create_time' => date('Y-m-d H:i:s')
                ];
                array_push($md_aclass_total, $aclass_total_install);

//                $md_map =[];
//                $start_day = strtotime("-1 years",$end_day);
//                array_push($md_map, ['cj_money', '>=', 500]);
//                array_push($md_map, ['cj_time', '>', 0]);
//                array_push($md_map,['cj_time','between',"$start_day,$end_day"]);
//                $zqx_cj_customer = DB::name('customer')->where($public_map)->where($md_map)->column('id'); //b类成交顾客
//                $lost_caseIds = $model->lost_case($zqx_cj_customer,$today);
//                $lost_caseIds_num = count($lost_caseIds);
//                $zqx_cjCustomerIds = array_diff($zqx_cj_customer,$lost_caseIds); //最终成交的顾客id
//                $zqx_cjCustomerIds_count  = count($zqx_cjCustomerIds);
//                $baoyou_ls = $this->baoyou_customer($zqx_cjCustomerIds,$today,$vv['shop_id']); //获取周期性保有以及流失人数
//
//                $baoyou  = $baoyou_ls['by'];
//                $zqxby_count = count($baoyou_ls['by']);//周期性保有人数
//
//                $lost = $baoyou_ls['ls'];
//                $zqxls_count = count($baoyou_ls['ls']);//周期性流失人数
//
//                $zqxby_rete = $zqx_cjCustomerIds_count > 0 ? bcmul(bcdiv($zqxby_count,$zqx_cjCustomerIds_count,4),100,2):0; //周期性保有率
//                $zqxls_rete = $zqx_cjCustomerIds_count > 0 ? bcmul(bcdiv($zqxls_count,$zqx_cjCustomerIds_count,4),100,2):0; //周期性流失率
//
//                $aclass_zq_install = [
//                    'market_id'=>$vv['market_id'],
//                    'shop_id'=>$vv['shop_id'],
//                    'shop_type'=>2,
//                    'date' =>$year.$month_str.$day_str,
//
//                    'ls_ya_customer_num' => $lost_caseIds_num,
//                    'ls_ya_customer_id' => empty($lost_caseIds) ? '' : implode(',', $lost_caseIds),
//                    'finally_cj_customer_num' => $zqx_cjCustomerIds_count,
//
//                    'by_periodicityl_num'=> $zqxby_count,
//                    'by_periodicity_customer_id'=>empty($baoyou)?'':implode(',',$baoyou),
//                    'by_periodicity_rate'=>$zqxby_rete,
//                    'ls_periodicity_num'=>$zqxls_count,
//                    'ls_periodicity_customer_id'=>empty($lost)?'':implode(',',$lost),
//                    'ls_periodicity_rate'=>$zqxls_rete,
//                    'create_time'=>date('Y-m-d H:i:s')
//                ];
//                array_push($md_aclass_zq,$aclass_zq_install);
            }
            DB::name('aclass_periodicity_log_new')->insertAll($md_aclass_zq);
//            DB::name('aclass_total_log_new')->insertAll($md_aclass_total);

//            DB::name('bclass_performance_log')->insertAll($mz_bclass_zq);
//            DB::name('bclass_total_log')->insertAll($mz_bclass_total);

        }
    }

    //b类顾客累计-周期性
    public function bclass_total_periodicity(){

        //第一批是太原市场  4
        //第二批是郑州市场 6
        //第三批是郑州万达市场 94 √
        //第四批是重庆市场 8
        //第五批是成都市场  9 √
        //第六批是天津市场  12 √
        //第七批是沈阳市场  13
        //第八批是哈尔滨市场  15
        //第九批是长春市场  14
        //第十批是昆明市场  16 √
        //第十一批是西安市场  19 √
        //第十二批是济南市场  21
        //第十三批是石家庄市场  23
        //第十四批是北京市场  25 √
        //第十五批是郑州公园茂市场 99 √
        //第十五批是金水市场   101 √
        //第十五批是三全市场  102 √
        //第十五批是郑东商业中心  103 √
        //第十五批是重庆光环市场  105   √
        $map =[
            ['status','=',1],
            ['type','<>','2'],
            ['market_id','in',[6]],
        ];
        $md_shop = DB::name('shop')->where($map)->where('shop_type','=',2)->field('shop_id,market_id')->select()->toArray();


        $year = date("Y");  // 当前年份
        $month = date("n"); // 当前月份（无前导零）
        $month = 10;
        $month_str = $month<10?'0'.$month:$month;
        $daysInMonth = date('t', mktime(0, 0, 0, $month, 1, $year)); //当前月份最大天数
        $model = new ReserveandLost();
        for($i=1;$i<=$daysInMonth;$i++){
            $day_str = $i<10?'0'.$i:$i;
            $md_bclass_total = $md_bclass_zq = [];
            //门店 累计保有-累计流失
            foreach($md_shop as $k=>$vv){
                $public_map = [
                    ['shop_id','=',$vv['shop_id']],
                    ['member_classification','=',72]
                ];
                $today = date($year.'-'.$month.'-'.$i);
                $end_day = strtotime($today." 23:59:59");
//                $md_map =[];
//                array_push($md_map, ['cj_money', '>=', 500]);
//                array_push($md_map, ['cj_time', '>', 0]);
//                array_push($md_map,['cj_time','<=',$end_day]);
//                $lj_cj_customer = DB::name('customer')->where($public_map)->where($md_map)->column('id'); //B类成交顾客
//
//                $lost_caseIds = $model->lost_case($lj_cj_customer,$today);
//                $lost_caseIds_num = count($lost_caseIds);  //流失优案 客户数
//
//                $lj_cjCustomerIds = array_diff($lj_cj_customer,$lost_caseIds); //最终成交的顾客id
//                $lj_cjCustomerIds_count  = count($lj_cjCustomerIds);
//
//                $baoyou_ls = $this->baoyou_customer($lj_cjCustomerIds,$today,$vv['shop_id']); //获取累计保有以及流失人数
//
//                $baoyou  = $baoyou_ls['by'];
//                $ljby_count = count($baoyou); //累计保有人数
//
//                $lost = $baoyou_ls['ls'];
//                $ljls_count = count($baoyou_ls['ls']);//累计流失人数
//
//                $ljby_rete = $lj_cjCustomerIds_count > 0 ? bcmul(bcdiv($ljby_count,$lj_cjCustomerIds_count,4),100,2):0;  //累计保有率
//                $ljls_rete = $lj_cjCustomerIds_count > 0 ? bcmul(bcdiv($ljls_count,$lj_cjCustomerIds_count,4),100,2):0;  //累计流失率
//
//                $bclass_total_install = [
//                    'market_id'=>$vv['market_id'],
//                    'shop_id'=>$vv['shop_id'],
//                    'shop_type'=>2,
//                    'date' =>$year.$month_str.$day_str,
//                    'ls_ya_customer_num' => $lost_caseIds_num,
//                    'ls_ya_customer_id' => empty($lost_caseIds) ? '' : implode(',', $lost_caseIds),
//                    'finally_cj_customer_num' => $lj_cjCustomerIds_count,
//                    'by_total_num'=> $ljby_count,
//                    'by_total_customer_id'=>empty($baoyou)?'':implode(',',$baoyou),
//                    'by_total_rate'=>$ljby_rete,
//                    'ls_total_num'=>$ljls_count,
//                    'ls_total_customer_id'=>empty($lost)?'':implode(',',$lost),
//                    'ls_total_rate'=>$ljls_rete,
//                    'create_time'=>date('Y-m-d H:i:s')
//                ];
//                array_push($md_bclass_total,$bclass_total_install);

                $md_map =[];
                $start_day = strtotime("-1 years",$end_day);
                array_push($md_map, ['cj_money', '>=', 500]);
                array_push($md_map, ['cj_time', '>', 0]);
                array_push($md_map,['cj_time','between',"$start_day,$end_day"]);
                $zqx_cj_customer = DB::name('customer')->where($public_map)->where($md_map)->column('id'); //A类成交顾客

                $lost_caseIds = $model->lost_case($zqx_cj_customer,$today);
                $lost_caseIds_num = count($lost_caseIds);
                $zqx_cjCustomerIds = array_diff($zqx_cj_customer,$lost_caseIds); //最终成交的顾客id
                $zqx_cjCustomerIds_count  = count($zqx_cjCustomerIds);
                $baoyou_ls = $this->baoyou_customer($zqx_cjCustomerIds,$today,$vv['shop_id']); //获取周期性保有以及流失人数

                $baoyou  = $baoyou_ls['by'];
                $zqxby_count = count($baoyou_ls['by']);//周期性保有人数

                $lost = $baoyou_ls['ls'];
                $zqxls_count = count($baoyou_ls['ls']);//周期性流失人数

                $zqxby_rete = $zqx_cjCustomerIds_count > 0 ? bcmul(bcdiv($zqxby_count,$zqx_cjCustomerIds_count,4),100,2):0; //周期性保有率
                $zqxls_rete = $zqx_cjCustomerIds_count > 0 ? bcmul(bcdiv($zqxls_count,$zqx_cjCustomerIds_count,4),100,2):0; //周期性流失率

                $bclass_zq_install = [
                    'market_id'=>$vv['market_id'],
                    'shop_id'=>$vv['shop_id'],
                    'shop_type'=>2,
                    'date' =>$year.$month_str.$day_str,
                    'ls_ya_customer_num' => $lost_caseIds_num,
                    'ls_ya_customer_id' => empty($lost_caseIds) ? '' : implode(',', $lost_caseIds),
                    'finally_cj_customer_num' => $zqx_cjCustomerIds_count,
                    'finally_cj_customer_id' => empty($zqx_cjCustomerIds) ? '' : implode(',', $zqx_cjCustomerIds),
                    'by_periodicityl_num'=> $zqxby_count,
                    'by_periodicity_customer_id'=>empty($baoyou)?'':implode(',',$baoyou),
                    'by_periodicity_rate'=>$zqxby_rete,
                    'ls_periodicity_num'=>$zqxls_count,
                    'ls_periodicity_customer_id'=>empty($lost)?'':implode(',',$lost),
                    'ls_periodicity_rate'=>$zqxls_rete,
                    'create_time'=>date('Y-m-d H:i:s')
                ];
                array_push($md_bclass_zq,$bclass_zq_install);
            }
            DB::name('bclass_periodicity_log_new')->insertAll($md_bclass_zq);
//            DB::name('bclass_total_log_new')->insertAll($md_bclass_total);


        }

    }


    //顾客累计消费
    public function customer_total_consumption(){
        //门诊
        //第一批是太原市场  4
        //第二批是郑州市场 6
        //第三批是郑州万达市场 94
        //第四批是重庆市场 8
        //第五批是成都市场  9
        //第六批是天津市场  12
        //第七批是沈阳市场  13
        //第八批是哈尔滨市场  15
        //第九批是长春市场  14
        //第十批是昆明市场  16
        //第十一批是西安市场  19
        //第十二批是济南市场  21
        //第十三批是石家庄市场  23
        //第十四批是北京市场  25
        //第十五批是郑州公园茂市场 99
        //第十五批是金水市场   101
        //第十五批是三全市场  102
        //第十五批是郑东商业中心  103
        //第十五批是重庆光环市场  105
        $map =[
            ['status','=',1],
            ['type','<>','2'],
//            ['market_id','in',[46]]
        ];
        $mz_shop = DB::name('shop')->where($map)->where('shop_type','=',1)->field('shop_id,market_id')->select()->toArray();

//        $md_shop = DB::name('shop')->where($map)->where('shop_type','=',2)->field('shop_id,market_id')->select()->toArray();
        $year = 2023;  // 当前年份
        $month = date("n"); // 当前月份（无前导零）
        $month = 12;
        $daysInMonth = date('t', mktime(0, 0, 0, $month, 1, $year)); //当前月份最大天数
        $month_str = $month<10?'0'.$month:$month;
        $error_customer = [];
        for($i=26;$i<=31;$i++){
            $md_insert_all =  [];
            $day_str = $i<10?'0'.$i:$i;
            $begin_time = strtotime($year.'-'.$month.'-'.$i);
            foreach($mz_shop as $kk=>$vv){
                $shop_id = $vv['shop_id'];
                $market_id = $vv['market_id'];
                $map =[
                    ['shop_id','=',$shop_id],
                ];
                $customer_id = DB::name('customer')->where($map)->field('id,member_classification,consumption,telephone')->select()->toArray();
                $customer_id = array_column($customer_id,null,'id');
                $where = [
                    ['status','=',2],
                    ['shop_id','=',$shop_id],
                    ['type','=',3],
                    ['refund_type','=','101.02'],
                    ['deal_time','=',$begin_time],
                ];
                $shoukuan = DB::name('shop_refund_order')->where($where)->field('sum(pay_amount) as total_amount,uid')->group('uid')->select()->toArray();
                $shoukuan_uids = array_column($shoukuan,'uid');
                $shoukuan = array_column($shoukuan,'total_amount','uid');

                $where = [
                    ['status','=',2],
                    ['shop_id','=',$shop_id],
                    ['type','=',1],
                    ['refund_type','<>','101.03'],
                    ['deal_time','=',$begin_time],
                ];
                $tuikuan = DB::name('shop_refund_order')->where($where)->field('sum(pay_amount) as total_amount,uid')->group('uid')->select()->toArray();
                $tuikuan_uids = array_column($tuikuan,'uid');
                $tuikuan = array_column($tuikuan,'total_amount','uid');

                $where = [
                    ['status','=',2],
                    ['shop_id','=',$shop_id],
                    ['type','=',2],
                    ['deal_time','=',$begin_time],
                ];
                $tuihuo = DB::name('shop_refund_order')->where($where)->field('sum(total_amount) as total_amount,uid')->group('uid')->select()->toArray();
                $tuihuo_uids = array_column($tuihuo,'uid');
                $tuihuo = array_column($tuihuo,'total_amount','uid');

                $where = [
                    ['status','=',2],
                    ['shop_id','=',$shop_id],
                    ['deal_time','=',$begin_time],
                ];
                $chuhuo = DB::name('shop_order')->where($where)->field('sum(order_amount) as total_amount,uid')->group('uid')->select()->toArray();
                $chuhuo_uids = array_column($chuhuo,'uid');
                $chuhuo = array_column($chuhuo,'total_amount','uid');

                $uids = array_merge($shoukuan_uids,$tuikuan_uids,$tuihuo_uids,$chuhuo_uids);
                $uids = array_unique($uids);

                foreach($uids as $key=>$val){
                    $shoukuan_money = isset($shoukuan[$val])?$shoukuan[$val]:0;
                    $tuikuan_money = isset($tuikuan[$val])?$tuikuan[$val]:0;
                    $chuhuo_money =  isset($chuhuo[$val])?$chuhuo[$val]:0;
                    $tuihuo_money =  isset($tuihuo[$val])?$tuihuo[$val]:0;
                    $consumption_sum = bcsub($shoukuan_money,$tuikuan_money,2); //当天的累计消费金额
                    $insert = [
                        'market_id'=>$market_id,
                        'shop_id'=>$shop_id,
                        'date'=>$year.$month_str.$day_str,
                        'customer_id'=>$val,
                        'level'=>0,
                        'collection_amount'=> $shoukuan_money,
                        'refund_amount'=>$tuikuan_money,
                        'shipment_amount'=>$chuhuo_money,
                        'return_goods_amount'=>$tuihuo_money,
                        'consumption_sum'=>$consumption_sum,
                        'create_time'=>date('Y-m-d H:i:s'),
                    ];

                    if(isset($customer_id[$val])){
                        $consumption = $customer_id[$val]['consumption']; //客户累计消费金额-customer 里边的
                        $phone =  $customer_id[$val]['telephone'];
                        $insert['customer_level'] = $customer_id[$val]['member_classification'];
                        $insert['customer_phone'] =$phone;
                        $insert['customer_consumption'] =$consumption;
                    }else{
                        array_push($error_customer,$val);
                        $customer_data = DB::name('customer')->where('id',$val)->field('id,member_classification,consumption,telephone')->find();
                        $insert['customer_level'] = '';
                        $insert['customer_phone'] = '';
                        $insert['customer_consumption'] = '';
                        if(!empty($customer_data)){
                            $insert['customer_level'] = $customer_data['member_classification'];
                            $insert['customer_phone'] = $customer_data['telephone'];
                            $insert['customer_consumption'] = $customer_data['consumption'];
                        }
                    }
                    array_push($md_insert_all,$insert);
                }
            }
            DB::name('customer_consumption_log')->insertAll($md_insert_all);
        }
        var_dump($error_customer);
    }

    //变更手机号
    public function change_customer_total_consumption(){
        //第一批是太原市场  4 √
        //第二批是郑州市场 6  √
        //第三批是郑州万达市场 94 √
        //第四批是重庆市场 8 √
        //第五批是成都市场  9
        //第六批是天津市场  12
        //第七批是沈阳市场  13
        //第八批是哈尔滨市场  15
        //第九批是长春市场  14
        //第十批是昆明市场  16
        //第十一批是西安市场  19
        //第十二批是济南市场  21
        //第十三批是石家庄市场  23
        //第十四批是北京市场  25
        //第十五批是郑州公园茂市场 99
        //第十五批是金水市场   101
        //第十五批是三全市场  102
        //第十五批是郑东商业中心  103
        //第十五批是重庆光环市场  105

       $data = DB::name('customer')->where('shop_id',73782775070582)->column('telephone','id');
       $customer_data = DB::name('customer_consumption_log')->where('customer_phone','')->where('shop_id',73782775070582)->group('customer_id')->column('customer_id');
       foreach($customer_data as $key=>$vv){
           if(isset($data[$vv])){
               $telephone = $data[$vv];
               $where = [
                   ['customer_phone','=',''],
                   ['customer_id','=',$vv],
               ];
               DB::name('customer_consumption_log')->where($where)->update(['customer_phone'=>$telephone]);
           }
       }





    }
    //门店周期性保有-流失 - 202401-20241010
    public function shop_total_periodicity(){
        //第一批是太原市场  4 √
        //第二批是郑州市场 6 √
        //第三批是郑州万达市场 94 √
        //第四批是重庆市场 8 √
        //第五批是成都市场  9 √
        //第六批是天津市场  12 √
        //第七批是沈阳市场  13 √
        //第八批是哈尔滨市场  15 √
        //第九批是长春市场  14 √
        //第十批是昆明市场  16 √
        //第十一批是西安市场  19 √
        //第十二批是济南市场  21 √
        //第十三批是石家庄市场  23  √
        //第十四批是北京市场  25  √
        //第十五批是郑州公园茂市场 99  √
        //第十五批是金水市场   101  √
        //第十五批是三全市场  102  √
        //第十五批是郑东商业中心  103  √
        //第十五批是重庆光环市场  105 √

        $map =[
            ['status','=',1],
            ['type','<>','2'],
            ['market_id','in',[94,99,101,102,103,105]],
        ];
//        $mz_shop = DB::name('shop')->where($map)->where('shop_type','=',1)->field('shop_id,market_id,create_time')->select()->toArray();

        $md_shop = DB::name('shop')->where($map)->where('shop_type','=',2)->field('shop_id,market_id,create_time')->select()->toArray();

        $year = date("Y");  // 当前年份
        $month = date("n"); // 当前月份（无前导零）
        $month = 10;
        $month_str = $month<10?'0'.$month:$month;

        $daysInMonth = date('t', mktime(0, 0, 0, $month, 1, $year)); //当前月份最大天数

        $model = new ReserveandLost();
        for($i=23;$i<=23;$i++){
            $day_str = $i<10?'0'.$i:$i;
            $mz_periodicity  = [];
            $md_periodicity  = [];
            //门店 周期性保有-累计流失
            foreach($md_shop as $k=>$vv){
                $md_where = $md_map = [
                    ['shop_id','=',$vv['shop_id']]
                ];
                $today = date($year.'-'.$month.'-'.$i);

                $end_day = strtotime($today." 23:59:59");
                $start_day = strtotime("-1 years",$end_day);
                array_push($md_map, ['cj_money', '>=', 500]);
                array_push($md_map, ['cj_time', '>', 0]);
                array_push($md_map,['cj_time','between',"$start_day,$end_day"]);

                $zqx_cj_customer = DB::name('customer')->where($md_map)->column('id');

                $lost_caseIds = $model->lost_case($zqx_cj_customer,$today);
                $lost_caseIds_num =  count($lost_caseIds);

                $zqx_cjCustomerIds = array_diff($zqx_cj_customer,$lost_caseIds); //最终成交的顾客id

                $zqx_cjCustomerIds_count  = count($zqx_cjCustomerIds);
                $baoyou_ls = $this->baoyou_customer($zqx_cjCustomerIds,$today,$vv['shop_id']); //获取周期性保有以及流失人数

                $baoyou  = $baoyou_ls['by'];
                $zqxby_count = count($baoyou_ls['by']);//周期性保有人数

                $lost = $baoyou_ls['ls'];
                $zqxls_count = count($baoyou_ls['ls']);//周期性流失人数

                $zqxby_rete = $zqx_cjCustomerIds_count > 0 ? bcmul(bcdiv($zqxby_count,$zqx_cjCustomerIds_count,4),100,2):0; //周期性保有率
                $zqxls_rete = $zqx_cjCustomerIds_count > 0 ? bcmul(bcdiv($zqxls_count,$zqx_cjCustomerIds_count,4),100,2):0; //周期性流失率

                $md_zq_install = [
                    'market_id'=>$vv['market_id'],
                    'shop_id'=>$vv['shop_id'],
                    'shop_type'=>2,
                    'date' =>$year.$month_str.$day_str,

                    'ls_ya_customer_num' => $lost_caseIds_num,
                    'ls_ya_customer_id' => empty($lost_caseIds) ? '' : implode(',', $lost_caseIds),
                    'finally_cj_customer_num' => $zqx_cjCustomerIds_count,

                    'by_periodicity_num'=> $zqxby_count,
                    'by_periodicity_customer_id'=>empty($baoyou)?'':implode(',',$baoyou),
                    'by_periodicity_rate'=>$zqxby_rete,
                    'ls_periodicity_num'=>$zqxls_count,
                    'ls_periodicity_customer_id'=>empty($lost)?'':implode(',',$lost),
                    'ls_periodicity_rate'=>$zqxls_rete,
                    'create_time'=>date('Y-m-d H:i:s')
                ];
                array_push($md_periodicity,$md_zq_install);
            }


            DB::name('shop_periodicity_log')->insertAll($md_periodicity);



//            foreach($mz_shop as $k=>$v){
//                $mz_where = $mz_map = [
//                    ['shop_id','=',$v['shop_id']]
//                ];
//                $today = date($year.'-'.$month.'-'.$i);
//                $end_day = strtotime($today." 23:59:59");
//                $start_day = strtotime("-1 years",$end_day);
//
//                array_push($mz_map,['cj_time','between',"$start_day,$end_day"]);
//
//                $zqx_cj_customer = DB::name('customer')->where($mz_map)->column('id');
//                $lost_caseIds = $model->lost_case($zqx_cj_customer,$today);
//                $zqx_cjCustomerIds = array_diff($zqx_cj_customer,$lost_caseIds); //最终成交的顾客id
//                $zqx_cjCustomerIds_count  = count($zqx_cjCustomerIds);
//                $baoyou_ls = $this->baoyou_customer($zqx_cjCustomerIds,$today); //获取周期性保有以及流失人数
//
//                $baoyou  = $baoyou_ls['by'];
//                $zqxby_count = count($baoyou_ls['by']);//周期性保有人数
//
//                $lost = $baoyou_ls['ls'];
//                $zqxls_count = count($baoyou_ls['ls']);//周期性流失人数
//
//                $zqxby_rete = $zqx_cjCustomerIds_count > 0 ? bcmul(bcdiv($zqxby_count,$zqx_cjCustomerIds_count,4),100,2):0; //周期性保有率
//                $zqxls_rete = $zqx_cjCustomerIds_count > 0 ? bcmul(bcdiv($zqxls_count,$zqx_cjCustomerIds_count,4),100,2):0; //周期性流失率
//
//                $mz_zq_install = [
//                    'market_id'=>$v['market_id'],
//                    'shop_id'=>$v['shop_id'],
//                    'shop_type'=>1,
//                    'date' =>$year.$month_str.$day_str,
//                    'by_periodicityl_num'=> $zqxby_count,
//                    'by_periodicity_customer_id'=>empty($baoyou)?'':implode(',',$baoyou),
//                    'by_periodicity_rate'=>$zqxby_rete,
//                    'ls_periodicity_num'=>$zqxls_count,
//                    'ls_periodicity_customer_id'=>empty($lost)?'':implode(',',$lost),
//                    'ls_periodicity_rate'=>$zqxls_rete,
//                    'create_time'=>date('Y-m-d H:i:s')
//                ];
//                array_push($mz_periodicity,$mz_zq_install);
//            }
//            DB::name('shop_periodicity_log')->insertAll($mz_periodicity);
        }
    }
    //门店累计性保有-流失
    public function shop_total_periodicity1(){

        //第一批是太原市场  4 √
        //第二批是郑州市场 6 √
        //第三批是郑州万达市场 94 √
        //第四批是重庆市场 8 √
        //第五批是成都市场  9 √
        //第六批是天津市场  12 √
        //第七批是沈阳市场  13 √
        //第八批是哈尔滨市场  15 √
        //第九批是长春市场  14 √
        //第十批是昆明市场  16 √
        //第十一批是西安市场  19 √
        //第十二批是济南市场  21 √
        //第十三批是石家庄市场  23 √
        //第十四批是北京市场  25  √
        //第十五批是郑州公园茂市场 99 √
        //第十五批是金水市场   101 √
        //第十五批是三全市场  102 √
        //第十五批是郑东商业中心  103 √
        //第十五批是重庆光环市场  105  √

        $map =[
            ['status','=',1],
            ['type','<>','2'],
        ];
//        $mz_shop = DB::name('shop')->where($map)->where('shop_type','=',1)->field('shop_id,market_id')->select()->toArray();

        $md_shop = DB::name('shop')->where($map)->where('shop_type','=',2)->field('shop_id,market_id')->select()->toArray();

        $year = date("Y");  // 当前年份
        $month = date("n"); // 当前月份（无前导零）
        $month = 11;
        $month_str = $month<10?'0'.$month:$month;

        $daysInMonth = date('t', mktime(0, 0, 0, $month, 1, $year)); //当前月份最大天数

        $model = new ReserveandLost();
        for($i=1;$i<=1;$i++) {
            $day_str = $i < 10 ? '0' . $i : $i;
            $mz_total = [];
            $md_total = [];
            //门店 累计保有-累计流失
            foreach ($md_shop as $k => $vv) {
                $public_map = [
                    ['shop_id', '=', $vv['shop_id']],
                ];
                $today = date($year . '-' . $month . '-' . $i);
                $end_day = strtotime($today . " 23:59:59");
                $md_map = [];
                array_push($md_map, ['cj_money', '>=', 500]);
                array_push($md_map, ['cj_time', '>', 0]);
                array_push($md_map, ['cj_time', '<=', $end_day]);
                $lj_cj_customer = DB::name('customer')->where($public_map)->where($md_map)->column('id'); //首次成交顾客id

                $lost_caseIds = $model->lost_case($lj_cj_customer, $today); //流失优案的客户id
                $lost_caseIds_num =  count($lost_caseIds);

                $lj_cjCustomerIds = array_diff($lj_cj_customer, $lost_caseIds); //最终成交的顾客id
                $lj_cjCustomerIds_count = count($lj_cjCustomerIds);

                $baoyou_ls = $this->baoyou_customer($lj_cjCustomerIds, $today,$vv['shop_id']); //获取累计保有以及流失人数

                $baoyou = $baoyou_ls['by'];
                $ljby_count = count($baoyou); //累计保有人数

                $lost = $baoyou_ls['ls'];
                $ljls_count = count($baoyou_ls['ls']);//累计流失人数

                $ljby_rete = $lj_cjCustomerIds_count > 0 ? bcmul(bcdiv($ljby_count, $lj_cjCustomerIds_count, 4), 100, 2) : 0;  //累计保有率
                $ljls_rete = $lj_cjCustomerIds_count > 0 ? bcmul(bcdiv($ljls_count, $lj_cjCustomerIds_count, 4), 100, 2) : 0;  //累计流失率

                $shop_total_install = [
                    'market_id' => $vv['market_id'],
                    'shop_id' => $vv['shop_id'],
                    'shop_type' => 2,
                    'date' => $year . $month_str . $day_str,
                    'ls_ya_customer_num' => $lost_caseIds_num,
                    'ls_ya_customer_id' => empty($lost_caseIds) ? '' : implode(',', $lost_caseIds),
                    'finally_cj_customer_num' => $lj_cjCustomerIds_count,
                    'by_total_num' => $ljby_count,
                    'by_total_customer_id' => empty($baoyou) ? '' : implode(',', $baoyou),
                    'by_total_rate' => $ljby_rete,
                    'ls_total_num' => $ljls_count,
                    'ls_total_customer_id' => empty($lost) ? '' : implode(',', $lost),
                    'ls_total_rate' => $ljls_rete,
                    'create_time' => date('Y-m-d H:i:s')
                ];
                array_push($md_total, $shop_total_install);
            }
            DB::name('shop_total_log')->insertAll($md_total);
        }
    }

    // 获取累计、周期性保有-流失
    public function baoyou_customer($customer_ids,$today,$shop_id){
        $start_time = $this->getlastThreeMonth($today);
        $end_time = strtotime($today);
        $ls = [];
        //先看有没有 收退款、退货
        $public_map = [
            ['deal_time','between',"$start_time,$end_time"],
            ['status','=',2],
            ['shop_id','=',$shop_id]
        ];

        $shop_refund_order_customer_id = DB::name('shop_refund_order')->where($public_map)->column('uid');
        $shop_refund_order_customer_id = array_unique($shop_refund_order_customer_id);
        $shop_refund_order_customer_id_diff = array_diff($customer_ids,$shop_refund_order_customer_id);
        if(!empty($shop_refund_order_customer_id_diff)){
            //再看有没有出货
            $shop_order_customer_id = DB::name('shop_order')->where($public_map)->column('uid');
            $shop_order_customer_id = array_unique($shop_order_customer_id);
            $shop_order_customer_id_diff = array_diff($shop_refund_order_customer_id_diff,$shop_order_customer_id);
            if(!empty($shop_order_customer_id_diff)){
                //再看有没有服务记录
                $where = [
                    ['customer_id','in',$shop_order_customer_id_diff],
                    ['create_time','between',"$start_time,$end_time"],
                    ['is_cancel','<>',2],
                    ['shop_id','=',$shop_id],
                ];
                $service_customer_id = DB::name('service_log')->where($where)->column('customer_id');
                $service_customer_id = array_unique($service_customer_id);
                $service_customer_id_diff = array_diff($shop_order_customer_id_diff,$service_customer_id);
                if(!empty($service_customer_id_diff)){
                    $by = array_diff($customer_ids,$service_customer_id_diff);
                    $ls =  $service_customer_id_diff;
                    return  ['by'=>$by,'ls'=>$ls];
                }
            }
        }
        return  ['by'=>$customer_ids,'ls'=>$ls];
    }


    public function getlastThreeMonth($today){
       return strtotime($today.' -3 month');
    }

    //验证数据
    public function verify(){
        $customer_id = 581919;
        $start_time = $this->getlastThreeMonth("2024-08-31");
        $end_time = strtotime("2024-08-31");
        $public_map = [
            ['deal_time','between',"$start_time,$end_time"],
            ['status','=',2]
        ];
        $map = [
            ['uid','=',$customer_id],
        ];
        $shop_refund_order_customer = DB::name('shop_refund_order')->where($public_map)->where($map)->find();
        $shop_order_customer_id = DB::name('shop_order')->where($public_map)->where($map)->find();
        $where = [
            ['customer_id','=',$customer_id],
            ['create_time','between',"$start_time,$end_time"],
            ['is_cancel','<>',2],
        ];
        $service_customer_id = DB::name('service_log')->where($where)->find();
        var_dump($shop_refund_order_customer,$shop_order_customer_id,$service_customer_id);

    }

    /******************旧的新单补单begin*********************/
    /*
         * @ 新单金额和补单金额的 计算 逻辑----川渝市场的 新单/补单业绩计算
         *
         * @ 门店新单/补单业绩计算 ：收款单（不含店转）的新单/补单 实收金额 【减去】 退款单（不含店转）的新单/补单 实收金额
         *                       【加上】  门诊转到门店的 新单/补单 实收金额 【减去】 退款单是店转的 新单/补单金额 【加上】 收款单是店转的新单/补单金额；
         *
         * @ 门珍新单/补单业绩计算 ：收款单（不含店转）的新单/补单 实收金额 【减去】 退款单（不含店转）的新单/补单 实收金额
         *                       【加上】  非疗程不含店转的 新单/补单 实收金额 【减去】 退款单是店转的 新单/补单金额 【加上】 收款单是店转的新单/补单金额；
         */
    public function sumShopPayMoneyNew($scene,$shopId,$shop_type,$startTime,$endTime,$person_id = 0){

        $map = $maps = [];
        if($person_id>0){
            array_push($maps,['r.sale_id','=',$person_id]);
            array_push($map,['sale_id','=',$person_id]);
        }
        switch ($scene) {
            case 'XD':

                $where['order_type']=1;
                $wheret['r.order_type']=1;
                break;

            case 'BD':

                $where['order_type']=2;
                $wheret['r.order_type']=2;
                break;

            default:

                break;

        }
        //收款单中的疤痕业绩 不含店转的业绩--01
        $receive = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            //->field('sum(g.pay_price * r.coefficient) as pay_amount')
            ->field('sum(g.pay_price) as pay_amount')
            ->where('r.shop_id','=',$shopId)
            ->where($maps)
            ->where($wheret)

            ->where('g.refund_mode','<>','06')

            ->where('r.type','=',3)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            ->find();

        // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


        //退款单中的疤痕业绩	--不含店转的业绩  --02
        $refund = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            //->field('sum(g.pay_price * r.coefficient) as pay_amount')
            ->field('sum(g.pay_price) as pay_amount')
            ->where('r.shop_id','=',$shopId)
            ->where($maps)
            ->where($wheret)

            ->where('g.refund_mode','<>','06')

            ->where('r.type','=',1)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            ->find();

        // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


        //门诊转店到 门店的 通过门店的归属ID 查询	--收款单 --03
        $receive_zd =Db::name('shop_refund_order')

            ->field('sum(pay_amount * coefficient) as pay_amount,id')
            ->where($map)
            ->where($where)

            ->where('referral_shop_id','=',$shopId)

            ->where('type','=',3)

            ->where('status','=',2)

            ->where('refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })->find();


        //退款单是店转的 疤痕/项目业绩查询  --04
        $refund_dz = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            ->field('sum(g.pay_price * r.coefficient) as pay_amount')
            ->where($maps)
            ->where($wheret)

            ->where('r.shop_id','=',$shopId)

            ->where('g.refund_mode','=','06')

            ->where('r.type','=',1)

            ->where('r.status','=',2)

            ->where('r.refund_type','<>','101.03')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            ->find();

        // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


        //收款单是店转的 疤痕/项目业绩---05
        $receive_dz = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            ->field('sum(g.pay_price * r.coefficient) as pay_amount')

            ->where('r.shop_id','=',$shopId)
            ->where($maps)
            ->where($wheret)

            ->where('g.refund_mode','=','06')

            ->where('r.type','=',3)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            ->find();

        // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


        //门诊收款单 是非疗程的 疤痕/项目业绩  --06
        $receive_mz =Db::name('shop_refund_order')

            ->field('sum(pay_amount * coefficient) as pay_amount')

            ->where($map)

            ->where($where)

            ->where('shop_id','=',$shopId)

            ->where('is_treatment','=',2)

            ->where('type','=',3)

            ->where('referral_shop_id','>',0)

            ->where('status','=',2)

            ->where('refund_type','<>','101.03')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })->find();

        if($shop_type==1){ //1是门诊 2是门店
            //return round($receive['pay_amount']-$refund['pay_amount'] +$receive_dz['pay_amount']+bcsub(0,$receive_mz['pay_amount'],2)+bcsub(0,$refund_dz['pay_amount']),2);
            return round(($receive['pay_amount']-$refund['pay_amount'] +$receive_dz['pay_amount']-$receive_mz['pay_amount']-$refund_dz['pay_amount']),2);
        }else{
            //实收金额 - 退款金额 + 门诊收钱分给店面的一半金额
            return round(($receive['pay_amount']-$refund['pay_amount'] +$receive_zd['pay_amount']+$receive_dz['pay_amount']-$refund_dz['pay_amount']),2);
        }
    }


    /*
	 * @ 疤痕业绩和项目业绩的 计算 逻辑----川渝市场的 疤痕和项目业绩计算
	 *
	 * @ 门店疤痕/项目业绩计算 ：收款单（不含店转）的疤痕/项目 实收金额 【减去】 退款单（不含店转）的疤痕/项目 实收金额
	 *                       【加上】  门诊转到门店的 疤痕/项目 实收金额 【减去】 退款单是店转的 疤痕/项目金额 【加上】 收款单是店转的疤痕/项目金额；
	 *
	 * @ 门珍疤痕/项目业绩计算 ：收款单（不含店转）的疤痕/项目 实收金额 【减去】 退款单（不含店转）的疤痕/项目 实收金额
	 *                       【加上】  非疗程不含店转的 疤痕/项目 实收金额 【减去】 退款单是店转的 疤痕/项目金额 【加上】 收款单是店转的疤痕/项目金额；
	 */
    public function sumShopPayMoneyNewMZ($scene,$shopId,$shop_type,$startTime,$endTime){
        switch ($scene) {
            case 'XD':

                $where['r.order_type']=1;
                break;

            case 'BD':

                $where['r.order_type']=2;
                break;

            default:

                break;

        }

        //收款单 收款类型是 收款 且不含收款方式不是店转的
        $receive = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')
            ->where($where)
            ->where('r.shop_id','=',$shopId)

            ->where('g.refund_mode','<>','06')

            ->where('r.type','=',3)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            // ->find();

            ->column('r.pay_amount as pay_amount','r.id');
        //->column('r.pay_amount * r.coefficient as pay_amount','r.id');

        //var_dump($receive);
        //退款单
        $refund = Db::name('shop_refund_order')->alias('r')

            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

            // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')

            ->where('r.shop_id','=',$shopId)

            ->where('g.refund_mode','<>','06')

            ->where('r.type','=',1)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })

            // ->find();

            //->column('r.pay_amount * r.coefficient as pay_amount','r.id');
            ->column('r.pay_amount  as pay_amount','r.id');

        // return round($receive['pay_amount'] -$refund['pay_amount'],2);

        $receive_sum = array_sum($receive);

        $refund_sum = array_sum($refund);

        return bcsub($receive_sum,$refund_sum,2);
    }

    /*******************旧的新单补单end*********************/

    //定时任务-跑客户积分兑换券状态
    public function change_point_status(){

        $map =[
            ['status','=',1],
            ['start_time','>',0],
            ['end_time','>',0],
        ];
        $time = time();
        $point_buy=DB::name('customer_point_goods_buy')->where($map)->field('end_time,id')->select()->toArray();
        $update_ids= [];

        foreach($point_buy as $k=>$v){
            if($v['end_time']<=$time){
                array_push($update_ids,$v['id']);
            }
        }

        if(!empty($update_ids)){
            $update = [
                'updated_at'=>time(),
                'status' =>0,
            ];
            $res = DB::name('customer_point_goods_buy')->whereIn('id',$update_ids)->update($update);
            if(!$res){
                echo "操作成功，错误ids为".json_encode($update_ids);die;
            }
        }
        echo "操作成功";

    }

    //问卷调查结果
    public function surveyResults(){

        $start_time = "";
        $end_time = "";
        $start_time = strtotime($start_time);
        $end_time = strtotime($end_time);

        $map = [
            ['create_time','between',"$start_time,$end_time"],
            ['questionnaire_id','=',8]
        ];

        $question_customer_arr = DB::name('question_customer')->where($map)->field('customer_id,shop_id,create_time')->select()->toArray();

        if(!empty($question_customer_arr)){
            $customer_ids = array_column($question_customer_arr,'customer_id');

            $customer = DB::name('customer')->whereIn('id',$customer_ids)->column('name,telephone','id');
            $shop = DB::name('shop')->where('status',1)->column('shop_name','shop_id');
            $point_goods_buy = DB::name('customer_point_goods_buy')->where('end_time',1740758399)->where('point_goods_id',26)->column('use_time','customer_id');

            foreach($question_customer_arr as $k=>&$v){

                $customer_name =  $customer_telephone = '暂无顾客信息';

                if(isset($customer[$v['customer_id']])){
                    $customer_name = $customer[$v['customer_id']]['name'];
                    $customer_telephone = $customer[$v['customer_id']]['telephone'];
                }

                $v['customer_name'] = $customer_name;
                $v['customer_telephone'] = $customer_telephone;

                $v['shop_name'] = isset($shop[$v['shop_id']])?$shop[$v['shop_id']]:'暂无门店信息';
                $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);


                $is_use = '未领取';
                $use_time = '暂无领取时间';
                if(!isset($point_goods_buy[$v['customer_id']])){
                    $is_use = $point_goods_buy[$v['customer_id']] >0 ?'已领取':'未领取';
                    $use_time = $point_goods_buy[$v['customer_id']]>0 ? date('y-m-d H:i:S',$point_goods_buy[$v['customer_id']]):'暂无领取时间';
                }

                $v['is_use']= $is_use;
                $v['use_time'] = $use_time;
            }
        }
        return $question_customer_arr;
    }

    //根据定时任务表去变更统计表数据-门店业绩
    public function shop_performance(){
        $mz_shop_ids = DB::name('shop')->where(['shop_type'=>1])->column('shop_id');
        $time = strtotime(date('Y-m-d'));
        $map =[
            ['order_deal_time','>',$time],
            ['is_adjustment','=', 0],
            ['type','=',1],
            ['shop_id','not in',$mz_shop_ids]
        ];
        $clientShopData= DB::name('clientshop_change_amount_log')
            ->where($map)
            ->field('shop_id,order_deal_time,market_id')
            ->group('shop_id,order_deal_time')
            ->select()->toArray();
        $mz_insert_all = $ids = [];
        $shopModel = new ShopModel();

        foreach($clientShopData as $k=>$v){
            $shop_id = $v['shop_id'];
            $md_shop_id = [$shop_id];
            $shopInfo= DB::name('shop')->where('shop_id',$shop_id)->field('market_id,shop_type')->find();
            $today = date('Ymd',$v['order_deal_time']);
            $startTime = strtotime($today);
            $endTime = strtotime($today." 23:59:59");

            $where  = [
                ['shop_id','=',$shop_id],
                ['date','=',$today],
            ];
            $shop_performance_id = DB::name('shop_performance_log')->where($where)->value('id');
            array_push($ids ,$shop_performance_id);

            /*****门店 begin*****/
            $md_bdyeji = $shopModel->shopPerform($md_shop_id,2,$startTime,$endTime,0,0); //补单
            $md_xdyeji = $shopModel->shopPerform($md_shop_id,1,$startTime,$endTime,0,0); //新单
            $shop_shi = $shopModel->ShopActualPerform($md_shop_id,$startTime,$endTime);//门店实收业绩
            $shop_zhuan = $shopModel->shopReferralPerform($md_shop_id,$startTime,$endTime); //门店转诊业绩
            $shopBHProject = $shopModel->shopPerform($md_shop_id,0,$startTime,$endTime,1); //门店疤痕业绩
            $shopPFXMProject = $shopModel->shopPerform($md_shop_id,0,$startTime,$endTime,2,2); //门店皮肤项目业绩
            $shopSTXMProject = $shopModel->shopPerform($md_shop_id,0,$startTime,$endTime,2,1); //门店身体项目业绩
            $shopQCDProject = $shopModel->shopPerform($md_shop_id,0,$startTime,$endTime,3); //门店青春痘业绩
            $shopHFPProject = $shopModel->shopPerform($md_shop_id,0,$startTime,$endTime,4); //门店护肤品业绩

            $md_insert = [
                'market_id'=>$shopInfo['market_id'],
                'shop_id'=>$shop_id,
                'shop_type'=>$shopInfo['shop_type'],
                'date' =>$today,
                'ss_amount'=> isset($shop_shi[$shop_id]) ? $shop_shi[$shop_id] : 0,
                'zz_amount'=>isset($shop_zhuan[$shop_id]) ? $shop_zhuan[$shop_id] : 0,
                'bd_amount'=>isset($md_bdyeji[$shop_id]) ? $md_bdyeji[$shop_id] : 0,
                'xd_amount'=>isset($md_xdyeji[$shop_id]) ? $md_xdyeji[$shop_id] : 0,
                'bh_amount'=>isset($shopBHProject[$shop_id]) ? $shopBHProject[$shop_id] : 0,
                'stxm_amount'=>isset($shopSTXMProject[$shop_id]) ? $shopSTXMProject[$shop_id] : 0,
                'pfxm_amount'=>isset($shopPFXMProject[$shop_id]) ? $shopPFXMProject[$shop_id] : 0,
                'qcd_amount'=>isset($shopQCDProject[$shop_id]) ? $shopQCDProject[$shop_id] : 0,
                'hfp_amount'=>isset($shopHFPProject[$shop_id]) ? $shopHFPProject[$shop_id] : 0,
                'create_time'=>date('Y-m-d H:i:s')
            ];
            array_push($md_insert_all,$md_insert);

        }
        DB::name('shop_performance_log')->insertAll($mz_insert_all);
        DB::name('clientshop_change_amount_log')
            ->where($map)->update(['is_adjustment'=>1,'update_time'=>time()]);
        if(!empty($ids)){
            DB::name('shop_performance_log')->whereIn('id',$ids)->delete();
        }

    }

    //根据定时任务表调整客户-客户累计消费
    public function customer_consumption(){
        $time = strtotime(date('Y-m-d'));
        $map =[
            ['order_deal_time','>',$time],
            ['is_adjustment','=', 0],
            ['type','=',2]
        ];
        $clientShopData= DB::name('clientshop_change_amount_log')
            ->where($map)
            ->field('shop_id,customer_id,order_deal_time,market_id')
            ->group('shop_id,customer_id,order_deal_time')
            ->select()->toArray();

        $customer_ids = array_column($clientShopData,'customer_id');

        $customer_data = DB::name('customer')->whereIn('id',$customer_ids)->column('customer_name,telephone,consumption,id,member_classification','id');

        if(!empty($clientShopData)){
            $customer_consumption_ids= [];
            foreach($clientShopData as $kk=>$vv) {
                $date= date('Ymd',$vv['order_deal_time']);
                $shop_id = $vv['shop_id'];
                $market_id = $vv['market_id'];
                $customer_id = $vv['customer_id'];
                $where  = [
                    ['shop_id','=',$shop_id],
                    ['market_id','=', $market_id],
                    ['date','=',$date],
                    ['customer_id','=',$customer_id]
                ];
                $consumptionData = DB::name('customer_consumption_log')->where($where)->find();

                array_push($customer_consumption_ids,$consumptionData['id']);

                $where = [
                    ['status', '=', 2],
                    ['shop_id', '=', $shop_id],
                    ['type', '=', 3],
                    ['refund_type', '=', '101.02'],
                    ['deal_time', '=', $date],
                    ['uid','=',$customer_id]
                ];
                $shoukuan = DB::name('shop_refund_order')->where($where)->field('sum(pay_amount) as total_amount,uid')->group('uid')->select()->toArray();
                $shoukuan = array_column($shoukuan, 'total_amount', 'uid');

                $where = [
                    ['status', '=', 2],
                    ['shop_id', '=', $shop_id],
                    ['type', '=', 1],
                    ['refund_type', '<>', '101.03'],
                    ['deal_time', '=', $date],
                ];
                $tuikuan = DB::name('shop_refund_order')->where($where)->field('sum(pay_amount) as total_amount,uid')->group('uid')->select()->toArray();
                $tuikuan = array_column($tuikuan, 'total_amount', 'uid');

                $where = [
                    ['status', '=', 2],
                    ['shop_id', '=', $shop_id],
                    ['type', '=', 2],
                    ['deal_time', '=', $date],
                    ['uid','=',$customer_id]
                ];
                $tuihuo = DB::name('shop_refund_order')->where($where)->field('sum(total_amount) as total_amount,uid')->group('uid')->select()->toArray();
                $tuihuo = array_column($tuihuo, 'total_amount', 'uid');

                $where = [
                    ['status', '=', 2],
                    ['shop_id', '=', $shop_id],
                    ['deal_time', '=', $date],
                    ['uid','=',$customer_id]
                ];
                $chuhuo = DB::name('shop_order')->where($where)->field('sum(order_amount) as total_amount,uid')->group('uid')->select()->toArray();
                $chuhuo = array_column($chuhuo, 'total_amount', 'uid');

                $shoukuan_money = isset($shoukuan[$customer_id]) ? $shoukuan[$customer_id] : 0;
                $tuikuan_money = isset($tuikuan[$customer_id]) ? $tuikuan[$customer_id] : 0;
                $chuhuo_money = isset($chuhuo[$customer_id]) ? $chuhuo[$customer_id] : 0;
                $tuihuo_money = isset($tuihuo[$customer_id]) ? $tuihuo[$customer_id] : 0;
                $consumption_sum = bcsub($shoukuan_money, $tuikuan_money, 2); //当天的累计消费金额

                $insert = [
                    'market_id' => $market_id,
                    'shop_id' => $shop_id,
                    'date' => $date,
                    'customer_id' => $customer_id,
                    'level' => 0,
                    'collection_amount' => $shoukuan_money,
                    'refund_amount' => $tuikuan_money,
                    'shipment_amount' => $chuhuo_money,
                    'return_goods_amount' => $tuihuo_money,
                    'create_time' => date('Y-m-d H:i:s'),
                    'shop_type'=>1,
                ];

                if(!empty($consumptionData)){
                    $insert['consumption_sum'] = bcadd($consumption_sum,$consumptionData['consumption_sum'],2);
                    $insert['customer_level'] = $consumptionData['customer_level'];
                    $insert['customer_phone'] = $consumptionData['customer_phone'];
                    $insert['customer_consumption'] = $consumptionData['customer_consumption'];
                }else{
                    $insert['consumption_sum'] = $consumption_sum;
                    $insert['customer_level'] = $customer_data[$vv['customer_id']]['member_classification'];
                    $insert['customer_phone'] = $customer_data[$vv['customer_id']]['telephone'];
                    $insert['customer_consumption'] = $customer_data[$vv['customer_id']]['consumption'];

                }
                array_push($md_insert_all, $insert);

            }

            DB::name('customer_consumption_log')->insertAll($md_insert_all);

            DB::name('clientshop_change_amount_log')
                ->where($map)->update(['is_adjustment'=>1,'update_time'=>time()]);

            if(!empty($customer_consumption_ids)){
                DB::name('customer_consumption_log')->whereIn('id',$customer_consumption_ids)->delete();
            }

        }
    }

    //定时任务-清零客户单项预存
    public function customer_balance_reset(){
        $where = [
            ['money|complimentary_money|shop_transfer_money','<>',0]
        ];
        $ids = [];
        $data = DB::name('customer_balance')->where($where)->select()->toArray();
        foreach($data as $k=>&$v){
            $bj_zj = bcadd($v['money'],$v['complimentary_money'],2);
            $bj_zj_dz = bcadd($v['shop_transfer_money'],$bj_zj,2);
            if($bj_zj_dz == 0){
                array_push($ids,$v['id']);
            }
        }
        if(!empty($ids)){
            $update = [
                'money'=>0,
                'complimentary_money'=>0,
                'shop_transfer_money'=>0,
            ];
            $res = DB::name('customer_balance')->whereIn('id',$ids)->update($update);
            var_dump('操作成功影响的行数:'.$res);die;
        }
        echo "暂无数据";

    }
    //定时任务-清零客户整体预存
    public function customer_balance_clear(){
        $where = [
            ['money|shop_transfer_money|complimentary_money','<>',0]
        ];
        $customer_ids = DB::name('customer_balance')->where($where)->column('customer_id');
        $customer_ids = array_unique($customer_ids);
        $ids = $success_ids =  [];
        foreach($customer_ids as $k=>$v){
            $balance = DB::name('customer_balance')
                ->where('customer_id',$v)
                ->where($where)
                ->column('money,complimentary_money,shop_transfer_money,id,shop_id,customer_id','balance_category_id');

            $bh_money = $bh_zj = $bh_dz = 0;
            $xm_money = $xm_zj = $xm_dz = 0;
            $qcd_money = $qcd_zj = $qcd_dz = 0;
            $hfp_money = $hfp_zj = $hfp_dz = 0;

            if(isset($balance[1])){
                $bh_money = $balance[1]['money'];
                $bh_zj = $balance[1]['complimentary_money'];
                $bh_dz = $balance[1]['shop_transfer_money'];
            }
            if(isset($balance[2])){
                $xm_money = $balance[2]['money'];
                $xm_zj = $balance[2]['complimentary_money'];
                $xm_dz = $balance[2]['shop_transfer_money'];
            }
            if(isset($balance[3])){
                $qcd_money = $balance[3]['money'];
                $qcd_zj = $balance[3]['complimentary_money'];
                $qcd_dz = $balance[3]['shop_transfer_money'];
            }
            if(isset($balance[4])){
                $hfp_money = $balance[4]['money'];
                $hfp_zj = $balance[4]['complimentary_money'];
                $hfp_dz = $balance[4]['shop_transfer_money'];
            }
            $bj_zj_dz = $bh_money + $bh_zj + $bh_dz + $xm_money + $xm_zj + $xm_dz + $qcd_money + $qcd_zj + $qcd_dz +  $hfp_money + $hfp_zj + $hfp_dz;

            if($bj_zj_dz == 0){
                array_push($ids,$v);
            }
        }
        if(!empty($ids)){
            $update = [
                'money'=>0,
                'complimentary_money'=>0,
                'shop_transfer_money'=>0,
            ];
            $res = DB::name('customer_balance')->whereIn('customer_id',$ids)->update($update);
            var_dump('操作成功影响的行数:'.$res);die;
        }
        echo "暂无数据";


    }
    //定时任务-去重顾客余额分类
    public function customer_balance_unique(){

        $data = DB::name('customer_balance')->group('shop_id,customer_id,balance_category_id')->having('count(*) >1')->select()->toArray();
        if(!empty($data)){
            $ids =array_column($data,'id');
            $res = DB::name('customer_balance')->whereIn('id',$ids)->delete();
            var_dump('操作成功影响的行数:'.$res);die;
        }
        echo "暂无数据";
    }

}
